Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda