[英]TypeScript: Is there a way to type a function so that it returns different types of results dynamically according to it params
[英]Typescript type which returns different types in function
我是打字稿和學習概念的新手。 在玩的時候,我被困在了一個場景中。 有一個名為 functonA 的函數,它基本上返回一個對象,其中函數的輸入具有來自 API 的響應。
type Combination = ResponseType1 | ResponseType2;
interface ResponseType1 {
firstAttr: string,
thirdAttr: string
}
interface ResponseType2 {
secondAttr: string,
thirdAttr: string
}
function someCondition() {
return true // or false
}
function functionA(response: Combination) {
return {
...(someCondition()) && { first: response.firstAttr }, // true condition
...(!someCondition()) && { second: response.secondAttr }, // false condition
...{ third: response.thirdAttr } // all case
}
}
這里的問題是我知道打字稿只能根據構建時的靜態分析來輸入內容。 最初我嘗試用兩個接口的聯合創建一個類型,但失敗了。 我不想在單個界面中將字段設為可選,因為這不是一個好方法。 API 可以根據某些條件返回不同的響應鍵。
現在我得到不存在類型錯誤,因為其他接口中不存在其中一個鍵。
打字稿版本使用:3.0.1
有人可以幫我找到相同的解決方案嗎? 請多多包涵。 任何幫助將非常感激。
如果您使用聯合類型,則如果該屬性並非對所有類型通用,則您無法訪問該屬性。
您可以在這里做的是在訪問之前檢查屬性。:
type Combination = ResponseType1 | ResponseType2;
interface ResponseType1 {
firstAttr: string,
thirdAttr: string
}
interface ResponseType2 {
secondAttr: string,
thirdAttr: string
}
function someCondition() {
return true // or false
}
function functionA(response: Combination) {
return {
...(someCondition()) && { first: ('firstAttr' in response ? response.firstAttr: undefined) }, // true condition
...(!someCondition()) && { second: ('secondAttr' in response ? response.secondAttr: undefined) }, // false condition
...{ third: response.thirdAttr } // all case
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.