确保对象具有每个枚举值作为键(Typescript)?

时间:2019-10-15 17:00:34

标签: 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

1 个答案:

答案 0 :(得分:1)

您可以像这样使用 class A < ActiveRecord::Base #uses db1 connection end class B < ActiveRecord::Base connects_to database: { writing: :db2, reading: :db2 } end 辅助类型(有关here的更多信息)

Record

等效于

type EnumMap<T extends string> = Record<T, string>

enter image description here