![](/img/trans.png)
[英]how to create an enum-like object with bigint initializers in typescript?
[英]How can I create union-like or enum-like behaviour from string constants in TypeScript?
我目前有一个包含颜色值的常量列表:
const gray = "#555"
const grayLight = "#777"
const primary1 = "#fff"
const primary2 = "#000"
我还有一个函数,它以对象的形式接收参数,我想为其创建一个接口。 其中一个参数应该是这些颜色的一个子集。
下面是一个使用union类型的示例。
interface props {
argument1: string
colorChoices: '#555' | '#777'
}
function myFunction(props: props): void {
//...
}
我知道枚举和联合类型不接受设计的计算(字符串)值。 所以以下方法不起作用:
const gray = "#555"
const grayLight = "#777"
enum colors {
gray = gray,
grayLight = grayLight,
}
type grays = gray | grayLight
我可以提出以下示例,这将使其类型安全并使其工作,但常量重复似乎不是一个合理的模式。
type gray = '#555'
const gray: gray = '#555'
type grayLight = '#777'
const grayLight: grayLight = '#777'
type grayScale = gray | grayLight
interface props {
argument1: string
colorChoices: grayScale
}
function myFunction(props: props): void {
//...
}
有没有办法实现这种行为而不重复我的常量值并只在一个地方有值?
您可以在常量上使用typeof
来获取常量的实际类型,因此您不需要为每个常量定义类型:
const gray = '#555'
const grayLight = '#777'
type grayScale = typeof gray | typeof grayLigh
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.