我有一个常量值:
const dataConst = 'constType'
我只想在某个接口中强制使用此值,但这是不可能的:
interface ExampleInterface {
data: dataConst
}
我试过了,似乎很管用,但我不知道这是不是最好的做法:
interface ExmapleInterface {
data: typeof dataConst
}
我试过了,也成功了,但我想知道我所做的是否是最好的做法.
我有一个常量值:
const dataConst = 'constType'
我只想在某个接口中强制使用此值,但这是不可能的:
interface ExampleInterface {
data: dataConst
}
我试过了,似乎很管用,但我不知道这是不是最好的做法:
interface ExmapleInterface {
data: typeof dataConst
}
我试过了,也成功了,但我想知道我所做的是否是最好的做法.
我相信做这件事没有好坏之分.你的例子只是实现你想要的许多方法之一.
也许解释一下您的示例为什么有效将是有用的.
const dataConst = 'constType'
将实际值赋给dataConst
常量.你还没有为这个const
显式地指定类型,所以类型是由TypeScript编译器推断的.它很聪明,所以它会分配一个"字符串文字",值为"constType".相反,如果你写类似于:let dataConst = 'constType'
,dataConst
的类型将是一个简单的string
,因为编译器知道这个值在future 可能会改变.
你不能使用
interface ExampleInterface {
data: dataConst
}
因为这是一个类型定义,只有"类型"可以进入其中.在本例中,dataConst
是实际值.
为了"检索"dataConst
常量的类型,我们可以使用typeof
.请记住,这是一个不同于Javascript的同名运算符.它只能在Typescript种类型的上下文中使用.
interface ExampleInterface {
data: typeof dataConst
}
那么现在有了这样的解释,还有没有其他方法呢?是.例如:
基于value
类型声明类型Value
const value = 'my-constant-value'
type Value = typeof value
interface Example {
prop: Value
}
或使用字符串文字声明Value
类型
type Value = 'my-constant-value'
const value: Value = 'my-constant-value'
interface Example {
prop: Value
}
或者,如果您不需要实际的常量值并且只使用类型就足够了
type Value = 'my-constant-value'
interface Example {
prop: Value
}
甚至是
interface Example {
prop: 'my-constant-value'
}