首页 > 解决方案 > 简洁地定义字符串及其联合类型

问题描述

我经常需要一组有效的字符串值和一个类型,所以我可以进行验证等等。我不想多次重复相同的字符串。我想出了这个:

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"

...但是我只是得到第一个字符串的类型。

标签: typescript

解决方案


number用而不是索引0

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

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

推荐阅读