每当我必须使用具有组合联合类型的对象时,typescript 会提示我尝试访问的属性,而且我也没有自动完成。例如这个:
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'
有什么方法可以缩小接口(interface)类型,从而获得更好的 IDE 体验?
最佳答案
interface A {
type:'A';
id: string;
value: number;
}
interface B {
type:'B';
result: string;
}
export type Types = A | B;
function test(obj: Types) {
if(obj.type==='B'){
obj.result;
}
}
你需要一个通用字段来教 TS 如何识别类型 A 或 B。
https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions
关于javascript - 为什么 typescript 会在类型联合上给出类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62910321/