Home > OS >  Type inference from Enum
Type inference from Enum

Time:07-14

I'd like to infer a property type from an enum like so:

enum Foo {
  One, Two
}

type Bar = {...}
type BarOne = Bar & {...}
type BarTwo = Bar & {...}

export type MyType<T extends Foo> = {
  data: // How do I set this type to be BarOne if Foo.One, BarTwo if Foo.Two, etc.?
}

Totally open to hearing a different approach if this is not ideal.

CodePudding user response:

You can use conditional typing if the number of your enum values are limited :

enum Foo {
  One, Two
}

type Bar = { foo: string }
type BarOne = Bar & { bar: string }
type BarTwo = Bar & { baz: string }

export type MyType<T extends Foo> = {
  data: T extends Foo.One ? BarOne : T extends Foo.Two ? BarTwo : never 
}

type FooOne = MyType<Foo.One> // { data: BarOne }

type FooTwo = MyType<Foo.Two> // { data: BarTwo } 

Playground

CodePudding user response:

Other possibility: A Map to associate an enum value to a type !

enum Foo {
  One, Two
}

type Bar = { foo: string }
type BarOne = Bar & { bar: string }
type BarTwo = Bar & { baz: string }

type FooMap = {
  [Foo.One]: BarOne
  [Foo.Two]: BarTwo
}

type FooOne = FooMap[Foo.One]  // { data: BarOne }
type FooTwo = FooMap[Foo.Two]  // { data: BarTwo } 

Playground

  • Related