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)
我如何顯示回傳型別foo()的打字稿?
已經嘗試Object.keys查看 typeOneProp 是否存在,但資料仍然為TypeOne | TypeTwo
dataintelisense 僅顯示name為屬性建議,因為這是兩種型別之間的共同屬性
// package.json
"typescript": "^4.4.4"
uj5u.com熱心網友回復:
使用in運算子檢查物件上是否存在該屬性(TS playground):
if('typeOneProp' in data) {
return data.typeOneProp;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439040.html
上一篇:字串擴展函式?
