geon
geon

Reputation: 8470

Defining both strings and their union type concisely

I often need to have a set of valid string values AND a type, so I can do validation and whatnot. I don't want to repeat the same string multiple times. I came up with this:

export const animals = [
    "cat" as const,
    "dog" as const
];

export type Animal = typeof animals[0];
// type Animal = "cat" | "dog"

Is there a more concise way? It is a bit noisy.

I'd like to do

export const animals = [
    "cat",
    "dog"
] as const;

export type Animal = typeof animals[0];
// type Animal = "cat"

...but then I just get the type of the first string.

Upvotes: 0

Views: 22

Answers (1)

Aplet123
Aplet123

Reputation: 35502

Index with number instead of 0:

export const animals = [
    "cat",
    "dog"
] as const;

export type Animal = typeof animals[number];
// type Animal = "cat" | "dog"

Upvotes: 2

Related Questions