Amr
Amr

Reputation: 1985

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?

Upvotes: 69

Views: 118554

Answers (5)

Blasfemizer
Blasfemizer

Reputation: 166

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.

Upvotes: 10

Joao
Joao

Reputation: 7476

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.

Upvotes: 118

Amr
Amr

Reputation: 1985

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;

Upvotes: 1

Valentin
Valentin

Reputation: 8074

Since strings, booleans and numbers are primitive types I don't think there is a simple way. If you would use a set of different object types, you could maybe come up with a super class and then specify that super class in the interface of your method. On the other hand, you could also use method overloading to specify different implementations for arrays of strings, booleans and integers.

Upvotes: 0

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220884

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

Upvotes: 3

Related Questions