如何在 Typescript 中使用不同长度的元组导出和重载函数参数列表

How to export and overload function argument list with tuples of different lengths in Typescript

不幸的是,在 Typescript 4.5.4 中,以下具有不同长度的不同元组的重载对我不起作用:

export function f<T1>    (t: [T1])   : any { ... }
export function f<T1,T2> (t: [T1,T2]): any { ... }

而用法是(在另一个文件中)

f(["hello"])
f(["hello", "world"])

打字稿给我:

TS2323: Cannot redeclare exported variable 'f'.

关于不引入多个函数名称(在顶层)的解决方法的任何想法?

问题是相似的,但答案似乎不再有效(编辑:有效,我误用了)并且不完全相同(在我的问题中给出了 Tuple type which may or may不影响正确答案)。

我不确定您是否需要重载的额外开销,但是您链接到的 仍然成立 – 重载应该声明多个类型签名但只实现函数一次。

TS playground

export function f<T1>(t: [T1]): T1
export function f<T1, T2>(t: [T1, T2]): T2
export function f(t: [unknown] | [unknown, unknown]) {
  if (t.length === 2) {
    return t[1]
  }
  return t[0]
}


  f([true]) // function f<boolean>(t: [boolean]): boolean (+1 overload)

  f([1, 'red']) // function f<number, string>(t: [number, string]): string (+1 overload)

  f([1, 'red', 2])
//  ^^^^^^^^^^^^^
//  No overload matches this call.
//    Overload 1 of 2, '(t: [unknown]): unknown', gave the following error.
//      Argument of type '[number, string, number]' is not assignable to parameter of type '[unknown]'.
//        Source has 3 element(s) but target allows only 1.
//      Overload 2 of 2, '(t: [unknown, unknown]): unknown', gave the following error.
//        Argument of type '[number, string, number]' is not assignable to parameter of type '[unknown, unknown]'.
//          Source has 3 element(s) but target allows only 2.