تأكد من أن الكائن يحتوي على كل قيمة من القيم في التعداد كمفتاح (TypeScript)؟


أريد من TypeScript أن يعطي خطأ عندما لا يحتوي الكائن على كل قيمة من قيم الـ enum كمفتاح. هل هذا ممكن؟

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}