【问题标题】:Typescript type which returns different types in function在函数中返回不同类型的打字稿类型
【发布时间】: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


    【解决方案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
       }
    }
    

    您可以查看文档here,特别是您可以查看名为working with union types的部分

    【讨论】:

    • 所以这是唯一可能的检查方法吗?在这种情况下,API 响应可能有超过 30 个键,这些键可能会因条件而异。
    • 是的,这是唯一的方法,因为文档也表明了这一点。
    猜你喜欢
    • 2015-08-10
    • 2022-01-12
    • 2022-07-07
    • 2019-02-13
    • 2021-09-17
    • 1970-01-01
    • 2019-07-06
    • 2020-06-29
    • 2019-05-30
    相关资源
    最近更新 更多