我经常需要有一组有效的字符串值和一个类型,这样我就可以进行验证等等。我不想重复同一个字符串多次。我想出了这个:
export const animals = [
"cat" as const,
"dog" as const
];
export type Animal = typeof animals[0];
// type Animal = "cat" | "dog"
有没有更简洁的方法?它有点吵。
我想做
export const animals = [
"cat",
"dog"
] as const;
export type Animal = typeof animals[0];
// type Animal = "cat"
但我只得到了第一个字符串的类型。
用number
而不是0
:索引
export const animals = [
"cat",
"dog"
] as const;
export type Animal = typeof animals[number];
// type Animal = "cat" | "dog"