简体   繁体   中英

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?

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.

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

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.

You can use the | and do the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM