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?
In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc). A union type allows us to define a variable with multiple types.
This is not possible.
TypeScript allows merging between multiple types such as interface with interface , enum with enum , namespace with namespace , etc.
TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With