我有使用类型脚本,并且有两个接口,接口1或接口2,例如:
export interface Interface1 {
propA: string;
propB: string;
}
export interface Interface12 {
propA: string;
propC: string;
}
以及返回实现可能接口之一的对象的方法,如下所示:
doSomething: (state): Interface1 | Interface2 | null => {
if (state === 1) {
return ObjectImplementingInterface1;
}
if (state === 2) {
return ObjectImplementingInterface2;
}
return null;
}
然后,我想使用该方法的结果并使用只存在于Interface2中的属性,例如:
const varExample = this.doSomething(this.s);
if (varExample) {
if ('type' in varExample && varExample.type === 'Interface1') {
this.importantResult = varExample.propA;
}
if ('type' in varExample && varExample.type === 'Interface2') {
this.importantResult = varExample.propC;
}
} else {
this.importantResult = 'someValue';
}
编译器不允许我使用proC,并抛出以下错误:
Property 'propC' does not exist on type '(Interface1 | Interface2) & Record<"type", unknown>'.
Property 'propC' does not exist on type 'Interface1 & Record<"type", unknown>'.
我怎样才能强迫TypeScrip知道这个对象一定是实现Interface2的对象呢?