1

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

From what I can tell, I can just use an enum. Thanks for you post.
Sure thing! edited the post and added some more info. Note the drawback of enums I've mentioned under Notes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.