繁体   English   中英

我可以将 Typescript function 参数定义为具有 boolean 类型或字符串吗?

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

我有这个 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;
    }
}

有没有一种方法可以在 typescript 中定义该操作的值可以为 boolean 或字符串?

是。 只需使用function而不是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!

它称为函数重载,您也可以对成员函数执行此操作。

您必须以经典的JavaScript方式获取参数类型:

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

为了声明有效的类型, 可以重载函数

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

我不相信您可以为这样的函数声明并分配给这样的变量,不; Typescript重载仅适用于类方法或常规函数。

您可以使用| 并执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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