1

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:

  • if driver == 'a' use InterfaceA
  • if driver == 'b' use InterfaceB

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
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

It may be helpful to point out that this pattern has a name and documentation: Discriminated unions.
type MyInterfaceA { is missing = btw
@GetOffMyLawn Thanks, fixed!
Thanks! Looks like this is working how I would like!
@Evert: why do you use type instead of interface for MyInterfaceA/B? Is there any advantage?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.