簡體   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