- Published on
Restrict Possible Values of a Type in TypeScript
- Authors
- Name
- Yair Mark
- @yairmark
Oftentimes you have a variable that can have a limited number of possible values but you do not want to have to create an enum for it. For example I have a variable that is a string and can only ever be the strings FOO
or BAR
:
type Fizz = 'FOO' | 'BAR'
If I then try to assign any other string to a variable of the Fizz
type I get a compile error:
// ----- error here
// Type '"dog"' is not assignable to type 'Fizz'.
const buzz: Fizz = 'dog'
Changing this to the following fixes this error:
const buzz: Fizz = 'FOO'
In TypeScript the type definition above compiles to nothing meaning that this literal check is only enforceable at compiletime and not at runtime. If you need this to be enforced at runtime rather use an enum:
enum Fiz {
FOO = 'FOO',
BAR = 'BAR',
}
The literal notiation above also works for other types not just strings:
enum Direction {
Left = 'Leftwards',
Right = 'Rightwards',
Up = 'Upwards',
Down = 'Downwards',
}
type SomeNum = 1 | 2
type Dir = Direction.Left | Direction.Right