[英]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.