Can I Specify Parameter Type as One of Many Types Instead of Any Type in TypeScript?
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;
Note that this is different from what OP asked for. These two examples have different meanings.
This seems a bit old question, but anyway, I came across it, and missed this other answer that I bring.
From TypeScript 1.4 seems that it is possible to declare multiple possible types for a function parameter like this:
class UtilsClass {
selectDom(element: string | HTMLElement):Array<HTMLElement> {
//Here will come the "magic-logic"
}
}
This is because of the new TypeScript concept of "union-types".
You can see more here.
You can use function overloads to do this:
class Thing {
public foo(x: number[]);
public foo(x: bool[]);
public foo(x: string[]);
public foo(x: any[]) {
// Note: You'll have to do type checking on 'x' manually
// here if you want differing behavior based on type
}
}
// Later...
var t = new Thing();
t.foo(someArray); // Note: External callers will not see the any[] signature
Another way to resolve this is to find the common methods and properties between the input types and declare an in-line type in the method declaration that holds these common methos and properties. Like this:
methodName(param1: { prop1: number; prop2: string; }, param2: { propA: bool; propB: string; } ): methodResultType;