[英]can typescript do union type assertion in this case?
typescript 在这种情况下可以做联合类型断言吗? 我想使用ab.a
或ab.b
或ab. hasOwnProperty
ab. hasOwnProperty
做type A
或type 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.