[英]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.a
或ab.b
或ab. hasOwnProperty
ab. hasOwnProperty
to do assertion of type A
or type B
? ab. hasOwnProperty
做type A
或type 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.