Search code examples
javascripttypescripttypesconstants

Reference constants in type definition


Typescript weirdness:

export type MyType = 0 | 1 | 2;

This works. But this does not:

export const ONE = 1;
export const TWO = 2;
export const THREE = 3;
export type MyType = ONE | TWO | THREE;

Solution

  • With the second example you are in typespace using a value (the declared consts) to declare a type. you need to use typeof ONE TWO or THREE. In the first example, 1 2 and 3 count as types themselves.