【问题标题】:TypeScript, bind multiple params to same typeTypeScript,将多个参数绑定到同一类型
【发布时间】:2016-11-23 00:20:24
【问题描述】:

有没有办法使用 TypeScript 实现以下目标?

function add(x, y) {
    return x + y;
}

我想要编译以下内容:

add(1, 2);
add("hello ", "world");

但我不想编译以下内容:

add(4, "world");
add("hello ", 4);

另请注意,我希望它仅针对字符串和数字进行编译。

【问题讨论】:

标签: typescript


【解决方案1】:

您可以使用泛型类型来做到这一点:

function add<T extends string | number>(x: T, y: T): T {
  return x + y;
}

add<string>("a", "b"); // OK
add<number>(5, 3); // OK
add<boolean>(true, false); // Type 'boolean' does not satisfy constraint 'string | number'

请注意,调用函数时并不总是需要提供泛型类型,只要它满足约束即可:

add("a", "b"); // OK
add(5, 3); // OK
add(5, "b"); // Type argument candidate 'number' is not a valid type argument because it is not a supertype of candidate 'string'.
add(true, "c"); // Type argument candidate 'boolean' is not a valid type argument because it is not a supertype of candidate 'string'.

如您所见,这是在说:

  • xy 必须是同一类型
  • 该类型必须是 stringnumber(或两者的扩展)

TypeScript 编译器足够聪明,无需在调用中指定泛型即可计算出类型(但您必须将它们放在定义中)。


如您所见,这是 TypeScript 编译器的问题。我有logged it on the TypeScript Github repo。

目前,您可以这样做:

function add<T extends string | number>(x: T, y: T): T {
    return <any>x + <any>y;
}

xy 仍然是 T 类型(由编译器确保),但我们欺骗它让我们对它们执行 +

【讨论】:

  • 遗憾的是它没有编译...Operator '+' cannot be applied to types 'T' and 'T'
  • 你使用的是什么版本的 TypeScript?这可能是编译器的问题。
  • @JamesMonger 不,即使在 typescript 2.2 (@next) 中它也不起作用。
  • 这是编译器@Erigotto 的问题,我已将其记录在TypeScript GitHub 上。 github.com/Microsoft/TypeScript/issues/12410
  • 我已经更新了解决方法的答案,直到它被修复@Erigotto。
【解决方案2】:

可以这样做:

function add<T extends string | number>(x: T, y: T): T;
function add(x: any, y: any) {
  return x + y;
}

let s = add("a", "b"); // fine
let n = add(1, 2); // fine
let n2 = add(1,"2"); // error

这就是你现在必须这样做的方式,尽管我很高兴@JamesMongar 打开了 GitHub 问题。如果 T 扩展了原始字符串或数字,那么 T 上的 + 运算符肯定是合法的。

【讨论】:

  • 不错的解决方案@Erigotto
猜你喜欢
  • 1970-01-01
  • 2019-02-08
  • 2020-11-09
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多