简体   繁体   English

typescript 在这种情况下可以做联合类型断言吗?

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

can typescript do union type assertion in this case? typescript 在这种情况下可以做联合类型断言吗? i want to use ab.a or ab.b or ab. hasOwnProperty我想使用ab.aab.bab. hasOwnProperty ab. hasOwnProperty to do assertion of type A or type B ? ab. hasOwnPropertytype Atype B的断言? how do i do?我该怎么办?

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
    }
}

Update your function as below:更新您的 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