【发布时间】:2021-12-17 21:19:43
【问题描述】:
我是打字稿和学习概念的新手。在玩的时候,我被困在一个场景中。有一个名为 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
}
}
这里的问题是我知道 typescript 只能在构建时基于静态分析键入内容。最初我尝试使用两个接口的联合创建一个类型,但失败了。我不想在单个界面中使字段可选,因为这不是一个好方法。 API 可以根据某些条件返回不同的响应键。
现在我得到的类型错误不存在,因为其中一个键在其他接口中不存在。
Typescript 版本使用:3.0.1
有人可以帮我找到相同的解决方案吗?请多多包涵。任何帮助将不胜感激。
【问题讨论】:
标签: javascript node.js typescript typescript-typings