mer*_*ere 3 typescript typescript-typings
我希望打字稿在对象没有每个枚举值作为键时抛出错误。是否可以?
type EnumMap<T> = { ??? }
enum Colors {
Red = 'Red',
Blue = 'Blue'
}
const obj1: EnumMap<Colors> = {
[Colors.Red]: 'roses',
[Colors.Blue]: 'violets'
} // works fine
const obj2: EnumMap<Colors> = {
[Colors.Red]: 'roses'
} // should throw error since Colors.Blue is not among obj2 keys
Run Code Online (Sandbox Code Playgroud)
Tho*_*aud 10
您可以像这样使用辅助类型(在此处Record阅读更多相关信息)
type EnumMap<T extends string> = Record<T, string>
Run Code Online (Sandbox Code Playgroud)
这相当于
type EnumMap<T extends string> = { [key in T]: string}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
970 次 |
| 最近记录: |