Alan2
Alan2

Reputation: 24572

Can I define a Typescript function parameter to have a type of boolean or string?

I have this function:

network = (action: boolean): void => {
    if (action) {
        this.action = action;
        this.net = true;
        this.netd = true;
    } else {
        this.action = null;
        this.net = false;
        this.netd = false;
    }
}

Is there a way that I can define in typescript that the action can have a value of boolean OR string?

Upvotes: 2

Views: 6366

Answers (4)

Jorciney
Jorciney

Reputation: 740

You can use the | and do the following:

const network = (action: boolean | string): void => {
    if(typeof action === 'string'){
    // do something
    } else {
    // do something else
    }
}

Upvotes: 2

Paleo
Paleo

Reputation: 23692

You have to get the parameter type in the classic JavaScript way:

network = (action: any): void => {
    if (typeof action === 'string')
        // action is a string
    else
        // action is a boolean
}

In order to declare the valid types, functions can be overloaded :

function myFunc(action: boolean): void;
function myFunc(action: string): void;
function myFunc(action: any): void {
    if (typeof action === 'string')
        // action is a string
    else
        // action is a boolean
}
myFunc('abc'); // ok
myFunc(false); // ok
myFunc(123); // error

Upvotes: 2

basarat
basarat

Reputation: 275927

Yes. Just use a function instead of var:

function network(action:boolean):void;
function network(action:string):void;
function network(action: any): void {
    if (action) {
        this.action = action;
        this.net = true;
        this.netd = true;
    } else {
        this.action = null;
        this.net = false;
        this.netd = false;
    }
}

network(''); //okay
network(true); // okay
network(12); // ERROR!

Its called function overloading and you can do this for member functions as well.

Upvotes: 2

Steve Wilkes
Steve Wilkes

Reputation: 7135

I don't believe you can for a function declared and assigned to a variable like that, no; Typescript overloads only apply to class methods or regular functions.

Upvotes: 0

Related Questions