Typescript 简明地定义字符串及其并集类型
我经常需要一组有效的字符串值和类型,这样我就可以进行验证等等。我不想重复同一个字符串多次。我想到了这个:Typescript 简明地定义字符串及其并集类型,typescript,Typescript,我经常需要一组有效的字符串值和类型,这样我就可以进行验证等等。我不想重复同一个字符串多次。我想到了这个: export const animals = [ "cat" as const, "dog" as const ]; export type Animal = typeof animals[0]; // type Animal = "cat" | "dog" 有没有更简洁的方法?有点吵 我想做
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"
…但是我只得到第一个字符串的类型。用
编号索引,而不是0
:
导出常量动物=[
“猫”,
“狗”
]作为常量;
出口类型动物=动物类型[数量];
//type Animal=“cat”|“dog”
用编号索引,而不是0
:
导出常量动物=[
“猫”,
“狗”
]作为常量;
出口类型动物=动物类型[数量];
//type Animal=“cat”|“dog”