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.
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) {
...
}
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.enum. Thanks for you post.Notes.