typescript - 简洁地定义字符串及其联合类型
问题描述
我经常需要一组有效的字符串值和一个类型,所以我可以进行验证等等。我不想多次重复相同的字符串。我想出了这个:
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"
推荐阅读
- python - 是否可以使用 MatPlotLib 和来自科学模型的数据创建图形?
- javascript - 查询字符串中的特殊字符在调用 axios post 时变成了空格
- python - 使用 Python 脚本自动创建 LXC 容器的几个问题
- javascript - JavaScript Throttle 总是返回函数
- docker - 使用 docker run 处理消息“未知标志:--build-arg”
- artificial-intelligence - 带柄切割模式识别的实现
- electron - 如何修复 ElectronNET.CLI 找不到模块“fs/promises”。需要堆栈错误
- python - BeautifulSoup - 阅读需要等待的页面
- python - 使用python在文件中添加特定日期
- python - 在 python 中,我如何运行并发生成器循环,当其中一个产生时暂停或终止?