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

Amr*_*Amr 28 javascript typescript

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

Joa*_*oao 55

Typescript 1.4引入了Union Types,所以答案现在是肯定的,你可以.

function myFunc(param: string[] | boolean[] | number[]): void;
Run Code Online (Sandbox Code Playgroud)

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


如果您需要多个特定类型的数组,您也可以使用联合类型:

function myFunc(param: (string|boolean|number)[]): void;
Run Code Online (Sandbox Code Playgroud)

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


小智 9

这似乎有点老问题,但无论如何,我遇到了它,并且错过了我带来的其他答案.

从TypeScript 1.4看来,可以为函数参数声明多种可能的类型,如下所示:

class UtilsClass {
    selectDom(element: string | HTMLElement):Array<HTMLElement> {
        //Here will come the "magic-logic"
    }
}
Run Code Online (Sandbox Code Playgroud)

这是因为"联合类型"的新TypeScript概念.

你可以在这里看到更多.