Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 简明地定义字符串及其并集类型_Typescript - Fatal编程技术网

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”