Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Specify Parameter Type as One of Many Types Instead of Any Type in 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?

like image 820
Amr Avatar asked Oct 08 '12 06:10

Amr


People also ask

Can a variable have multiple types TypeScript?

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.

Can you pass a type as a parameter TypeScript?

This is not possible.

Is it possible to combine types in TS?

TypeScript allows merging between multiple types such as interface with interface , enum with enum , namespace with namespace , etc.

How do I assign two TypeScript types?

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.


2 Answers

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.

like image 194
Joao Avatar answered Sep 20 '22 11:09

Joao


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.

like image 35
Blasfemizer Avatar answered Sep 22 '22 11:09

Blasfemizer