網站搜尋

確保物件具有每個枚舉值作為鍵(Typescript)?


我希望當物件沒有每個列舉值作為鍵時,TypeScript 能拋出錯誤。這有可能嗎?

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

你可以像這樣使用 Record 輔助類型(在這裡閱讀更多相關資訊)

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

相當於

type EnumMap<T extends string> = { [key in T]: string}