网站搜索

javascript - Typescript 类型,用于在函数中返回不同类型


我刚接触 TypeScript,正在学习相关概念。在尝试过程中,我遇到了一个情景。有一个叫做 functionA 的函数,它基本上返回一个对象,其中函数的输入会从 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

有人能帮我找到同样问题的解决方案吗?请耐心等待。任何帮助都将非常感激。

答案#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
   }
}

你可以在这里查看文档,尤其可以查看名为“使用联合类型”的部分