[英]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.