【发布时间】:2020-11-04 16:24:05
【问题描述】:
每当我必须使用具有组合联合类型的对象时,打字稿都会抱怨我尝试访问的属性并且我也没有获得自动完成功能。例如:
interface A {
id: string;
value: number;
}
interface B {
result: string;
}
export type Types = A | B;
function test(obj: Types) {
obj.result; // want to work with obj as though it implements interface B
}
当我从 typescript 访问 result、id 和 value 时出现错误:
Property 'result' does not exist on type 'Types'.
Property 'result' does not exist on type 'A'
有什么方法可以缩小接口类型,从而获得更好的 IDE 体验?
【问题讨论】:
-
您需要type guard 以某种方式。
-
因为
result只存在于B上,如果你的obj是A,那么访问result就会返回undefined
标签: javascript typescript union-types