I want to initialise an array with values based on a type:
type Pets = 'dog' | 'cat';
const PETS: Array<Pets> = []; // ['dog', 'cat'];
Pets
is an ever-changing type, which I need to be represented in PETS
.
CodePudding user response:
You could initialize the constant and then create the type based on this constant:
const PETS = ['dog', 'cat'] as const
type Pets = typeof PETS[number];
It's the other way around, but still you only need to write it once.
CodePudding user response:
It's a bit trickier with types.
There's the option A_A proposed which is somewhat common.
If it doesn't necessarily have to be a type
, you can replace it with an enum
which will allow you to iterate over it's values.
Example:
enum Pets {
Cat = 'cat',
Dog = 'dog',
}
const pets: Pets[] = (Object.keys(Pets) as Array<keyof typeof Pets>).map(x => Pets[x])
// pets = ['cat', 'dog']
To access values in an enum
you can either use their string value or the lefthand property.
For example, both of these should work:
const pets: Pets[]
// First option:
if (pets[0] === 'cat') {
...
}
// Second option:
if (pets[0] === Pets.Cat) {
...
}
Notes:
- Unlike
const enum
(which is not iterable),enum
types add some JS code to the bundle (which TS normally shouldn't do), keep this in mind going forward.
For instance, if you have a great number of regular enums in your project it might add quite a bit of code to your bundle, whether or not that's ok depends on you.