1

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
}

1 Answer 1

4

You can use a discriminated union type:

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

Playground Link

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

Comments

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.