interface TypeOne {
name: string;
typeOneProp: any;
}
interface TypeTwo {
name: string;
typeTwoProp: any;
}
async function foo(): Promise<TypeOne | TypeTwo> {
return this.service.get();
}
async function bar(): Promise<any> {
const data = await foo();
if(data?.typeOneProp) { // errors shown below
return data.typeOneProp;
}
}
Property 'typeOneProp' does not exist on type 'TypeOne | TypeTwo'.
Property 'typeOneProp' does not exist on type 'TypeTwo'. ts(2339)
how can i show typescript which return type foo()
had?
already tried Object.keys
to see if typeOneProp exists but data remains as TypeOne | TypeTwo
data
intelisense only shows name
as a property sugestion as is a common property between both types
// package.json
"typescript": "^4.4.4"
CodePudding user response:
Use the in
operator to check if the property exists on the object (TS playground):
if('typeOneProp' in data) {
return data.typeOneProp;
}