且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以在TypeScript中将参数类型指定为多种类型之一而不是任何类型吗?

更新时间:2023-10-15 09:02:22

Typescript 1.4引入了联盟类型所以答案现在是 是的,你可以

Typescript 1.4 introduced Union Types so the answer now is yes, you can.

function myFunc(param: string[] | boolean[] | number[]): void;

使用除指定类型之外的其他类型将触发编译时错误。

Using other type than the ones specified will trigger a compile-time error.

如果你想要一个包含多种特定类型的数组,你也可以使用联合类型:

If you want an array of multiple specific types, you can use Union Types for that as well:

function myFunc(param: (string|boolean|number)[]): void;

请注意,这与OP要求的不同。这两个例子有不同的含义。