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

132
Visualizações
Dynamically determine the correct type of data with a type hint

Is it possible to interpret data differently based on a 'type-field'?

I am loading data (all from the same file). I know the type of the data, and what the type definitions look like. With the current union approach, it'd always show all fields, but I'd like to be able to automatically be able to determine which type applies. I could cast the type during runtime, but that's not ideal.

Not sure if I am pushing TS a bit too much here, and if it instead should live in the actual loading/parsing logic?

Current approach

enum MyTypes {
  TypeA = "A",
  TypeB = "B",
}
type IData = {
  type: MyTypes;
  data: IDataAllTypes <---- force the type to be `IDataTypeA` if the type field is `TypeA`
}
type IDataAllTypes = IDataTypeA | IDataTypeB

type IDataTypeA = {
  id: string
  age: number
  foo: string[]
}

type IDataTypeB = {
  id: string
  name: string
  bar: string[]
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This is called a discriminated union. It's a union type where all members have a common field that can be used to enforce the rest of the type.

You can declare IData like this:

type IDataA = {
    type: MyTypes.TypeA,
    data: IDataTypeA
}

type IDataB = {
    type: MyTypes.TypeB,
    data: IDataTypeB
}
type IData = IDataA | IDataB

Now this works like you expect:

const testA: IData = { type: MyTypes.TypeA, data: { id: 'qwe', age: 123, foo: ['a'] }}
const testB: IData = { type: MyTypes.TypeB, data: { id: 'qwe', name: 'asd', bar: ['b'] }}

// Type error. Can't pair type A with values from type B
const testFail: IData = { type: MyTypes.TypeA, data: { id: 'qwe', name: 'asd', bar: ['b'] }}

Playground

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do it like this

enum MyTypes {
  TypeA = "A",
  TypeB = "B",
}

type IDataTypeA = {
  id: string
  age: number
  foo: string[]
}

type IDataTypeB = {
  id: string
  name: string
  bar: string[]
}

IDataA {
  type: MyTypes.TypeA,
  data: IDataTypeA,
}

IDataB {
  type: MyTypes.TypeB,
  data: IDataTypeB,
}

IDataAllTypes = IDataA | IDataB;
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