Norayr Ghukasyan
Norayr Ghukasyan

Reputation: 1418

Conditional types inside interface

I have an Interface with this shape

interface MyInterface {
    otherVal1: string;
    otherVal2: string;
    ...;
    container: 'bank' | 'creditCard' | 'investment'
    type: 'option1' | 'option2' | 'option3' ...
} 

I need to set types for type property based on the container property. For example, if the container value is bank, then the options for type are for example option1 and option2.In case of creditCard, the options ara option3, option4 and option5 and so on.

I can't find any implementation similar to my case both in the docs and on StackOverflow.

Upvotes: 0

Views: 53

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

You'd use a union type:

type MyInterface =
    {container: "bank", type: "option1" | "option2"}
    |
    {container: "creditCard", type: "option3" | "option4" | "option5"}
    |
    {container: "investment", type: "option6" | "option7"}
;

When using it, you'd use a type guard checking container so TypeScript knows the valid types for type.

Upvotes: 2

Related Questions