我可以在TypeScript中将参数类型指定为多种类型之一而不是任何类型吗? [英] Can I Specify Parameter Type as One of Many Types Instead of Any Type in TypeScript?

查看:424
本文介绍了我可以在TypeScript中将参数类型指定为多种类型之一而不是任何类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在TypeScript的方法声明中,参数可以是字符串,布尔值或数字的类型。我是否必须将其声明为任何[],或者是否有办法将输入类型限制为这三种类型?

In a method declaration in TypeScript, the parameter could be of type array of strings, booleans, or numbers. Do I have to declare it as any[] or is there a way to limit the input type as on of these three types?

推荐答案

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要求的不同。这两个例子有不同的含义。

这篇关于我可以在TypeScript中将参数类型指定为多种类型之一而不是任何类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆