繁体   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