简体   繁体   中英

Typescript type which returns different types in function

I am new to typescript and learning the concepts. While playing around, I was stuck in a scenario. There is a function called functonA which basically returns an object where the input to function has a response from an 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
   }
}

The problem here is I know that typescript can only type things based on the static analysis at build time. Initially I tried creating a type with Union of two Interfaces but failed miserably. I don't want to make fields optional in a single interface since that won't be a nice approach. API can return difference response key's based on some condition.

Now I am getting doesn't exists on type error since one of the keys is not there in other Interface.

Typescript version using: 3.0.1

Can somebody help me to find a solution for the same? please bear with me. Any help would be really appreciated.

You cannot access a property if it is not common for all types if you use a union type.

What you can here is check for property before accessing it.:

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
   }
}

you can check the documentation here , and especially you can check the part called working with union types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM