Objenin her enum değerine anahtar olarak sahip olduğundan emin olun (Typescript)?


Typescript'in, bir nesnenin her enum değerini anahtar olarak içermediğinde hata vermesini istiyorum. Bu mümkün mü?

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

Cevap #1

Record yardımcı tipini (daha fazlasını buradan okuyabilirsiniz) şu şekilde kullanabilirsiniz

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

ki bu, ...in eşdeğeridir

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

İlgili makaleler