Dynamically determine the correct type of data with a type hint

Viewed 52

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[]
}
2 Answers

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

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;
Related