繁体   English   中英

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

[英]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"])

Typescript 给了我:

TS2323:无法重新声明导出的变量“f”。

在不引入多个 function 名称(在顶层)的情况下,关于解决方法的任何想法?

这个问题很相似,但答案似乎不再起作用并且不完全相同(在我的问题中给出了元组类型,它可能对正确答案产生影响,也可能不产生影响)。

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

TS游乐场

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM