ruvi ruvi - 2 months ago 6
TypeScript Question

Type that allows only one of listed value in typeScript

Is there type in typeScript that allows only one of listed value ?

What I want:



typethatiwant Animals = ['cat', 'dog'];

let myAnimal: Animals = 'cat'; // good
myAnimal = 'dog'; // good
myAnimal = 'hamster'; // error because 'hamster' not 'cat' or 'dog'




Answer

An union type combined with string literals

type Animals = 'cat' | 'dog'

See it in the playground