簡體   English   中英

typescript 在這種情況下可以做聯合類型斷言嗎?

[英]can typescript do union type assertion in this case?

typescript 在這種情況下可以做聯合類型斷言嗎? 我想使用ab.aab.bab. hasOwnProperty ab. hasOwnPropertytype Atype B的斷言? 我該怎么辦?

export interface A extends Object {
    a: string;
}

export interface B extends Object {
    b: number;
}

export type AorB = A | B;

function test(ab: AorB) {
    // can ts auto predict this ?
    if (ab.hasOwnProperty('a')) {
        ab.a // type error
    }
}

更新您的 function 如下:

function test(ab: AorB) {
    // can ts auto predict this ?
    if ('a' in ab) {
        console.log(ab.a);
    }
}

暫無
暫無

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

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