TL;DR
const STATUS = constList('AVAILABLE', 'BOUGHT', 'REJECTED')
type Status = keyof typeof STATUS;
// type Status = 'AVAILABLE' | 'BOUGHT' | 'REJECTED';
Itβs always better to work with constants instead of having strings all over your code. In TS we can implement a list of constants with enums like this:
// π Good
enum STATUS {
AVAILABLE = 'AVAILABLE',
BOUGHT = 'BOUGHT',
REJECTED = 'REJECTED',
}
type Status = keyof typeof STATUS;
With this simple solution, we have the list and the corresponding type, great!
The main issue is enums is that we need to repeat the name of the value as a string. To solve this we can implement a helper function like the following:
function constList<T extends string>(
...args: Array<T>
): {
[K in T]: K;
} {
return args.reduce((accumulator, value) => {
accumulator[value] = value;
return accumulator;
}, Object.create(Object.prototype));
}
This function converts the list of parameters in an object with shape:
{
AVAILABLE: 'AVAILABLE',
BOUGHT: 'BOUGHT',
REJECTED: 'REJECTED'
}
Then, we can use the function like this:
// ππ Better!
const STATUS = constList('AVAILABLE', 'BOUGHT', 'REJECTED')
type Status = keyof typeof STATUS;
This way is simpler π.
Also you can get types of an array in this way
const animals = ['cat', 'dog', 'mouse'] as const
type Animal = typeof animals[number]
// type Animal = 'cat' | 'dog' | 'mouse'