cubefox
cubefox

Reputation: 1301

typescript set type depending on value

I have a function that takes in an optional variant and a value. If the variant is multi the user needs to use a tuple, otherwise a number. Is there any way to type this dynamically? Conceptually it should work like this:

interface SomeInterface{
  variant?: 'single' | 'multi'
  // pseudocode
  value: variant === 'multi' ? [number,number] : number
}

Upvotes: 1

Views: 155

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249586

You can use a discriminated union type:

type SomeInterface = {
    variant?: 'single'
    value: number
} | {
    variant: 'multi',
    value: [number,number]
} 

Playground Link

Upvotes: 4

Related Questions