TypeScript,将多个参数绑定(bind)到同一类型

标签 typescript generics

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

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

我要编译以下内容:

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

但我不想编译以下内容:

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

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

最佳答案

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

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 类型(由编译器确保)但是我们欺骗它让我们做 + 在他们身上。

关于TypeScript,将多个参数绑定(bind)到同一类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40723718/

相关文章:

typescript - TypeScript 中的非破坏性类型断言

typescript - 用常量重载

从第 n 个子级 2 到父级的 Angular 输出变量

使用泛型实现接口(interface)的 Java 抽象类

java - 如何获取通用类型的列表或者如果不可能如何解决提供的任务?

C# Func<> 和泛型

javascript - VS Typescript 找不到本地文件夹

javascript - Angular - 可观察检查值是否存在

java - 在 Java 中如何使用泛型引用嵌套类型?

带有 super 的 Java 通配符