Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!