Get Off My Lawn
Get Off My Lawn

Reputation: 36311

Conditional type based on the value of another key

Is there a way to use an interface based on the value of another key?

So, I would like options to use a particular interface if driver equals a particular value:

I thought something like this might work but it doesn't.

export interface InterfaceA {}
export interface InterfaceB {}

export interface MyInterface {
  driver: string
  root: string
  options: driver == 'a' ? InterfaceA : InterfaceB
}

Upvotes: 1

Views: 93

Answers (1)

Evert
Evert

Reputation: 99543

There's a few different ways to do this, but I tend to take this approach as it gives me the easiest to read error messages:

export interface InterfaceA {}
export interface InterfaceB {}

type MyInterfaceA = {
  driver: 'a',
  root: string,
  options: InterfaceA,
}
type MyInterfaceB = {
  driver: 'b',
  root: string,
  options: InterfaceB,
}
export type MyInterface = MyInterfaceA | MyInterfaceB;

As far as I know these have to be a type not interface, as interfaces don't support union types. (thank you @jcalz).

It's possible to write the above without duplicating the root property, which can be useful if there are more common properties, but I end up duplicating everything anyway as error messages are a lot clearer when avoiding nested unions and intersects.

Upvotes: 1

Related Questions