簡體   English   中英

打字稿聯合類型打字員

[英]typescript union types typeguards

我有一個這樣的代碼段:

function test(): any[] | string {
  return [1,2]
}

let obj: any[]  = test();

這在vscode中產生以下錯誤:

[ts] Type 'string | any[]' is not assignable to type 'any[]'.
       Type 'string' is not assignable to type 'any[]'.

我知道我必須采取某種防范措施,但不能理解這里的概念。 有人嗎

函數test()返回的“更廣泛”類型,由變量聲明並作為typescript的any[]到目前為止無法提前驗證函數將始終返回數組實例-它抱怨。 要解決此問題,您實際上應該使用您提到的打字機 ,例如

function test(): any[] | string
{
    return [1, 2];
}

let val = test();
if (val instanceof Array)
{//no error here
    let obj: any[] = val;
}

使用類型保護,Typescript可以縮小聯合類型的范圍。 您可以簡單地使用縮小條件,但是添加類型保護功能可為您提供額外的可重用性和靈活性:

function isAnyArray(value: any[] | string): value is any[] {
    return value instanceof any[];
}

因此,您可以定期進行分配,然后在類型防護提供的范圍內工作:

let obj: string | any[] = test();

if (isAnyArray(obj)) {
    //Use obj here as if it were an any[]
}

由於您在多個地方使用聯合,因此可以為其定義一個類型並代替手動聯合類型使用它:

type StringOrAnyArray = string | any[];
//...
function isAnyArray(value: StringOrAnyArray): value is any[] {
    return value instanceof any[];
}
//...
let obj: StringOrAnyArray = test();

if (isAnyArray(obj)) {
    //Use obj here as if it were an any[]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM