对象键的强制类型

enforce type of Object's Key

我正在尝试创建一个只能包含特定键的字典对象。

我想将键限制为 type rate

type rate = 60 | 30 | 20 | 15 | 12 | 10 | 6 | 5 | 4 | 3 | 2 | 1;
//so i can do this
const d = {
  60 : 100, //fine
  20 : 150, //fine
  11 : 120, //<--- detect as not allowed
}

我尝试了以下方法并尝试检测错误类型,例如 11,但它强制对象具有 所有 键,这是我没有的想要。

const d2 : Record<rate, number> = {
  60 : 100,
  20 : 150,
  11 : 120, //<--- not allowed
} //<--- error: Type is missing the properties 60, 30, 20, 15,...

我需要一个允许这样的类型:

const ej1 : T = {
  60 : 10,
  20 : 11,
}
const ej2 : T = {
  30 : 50,
  10 : 60,
  2  : 4,
}

而不是这个:

const ej3 : T = {
  10 : 170,
  11 : 150, //<--- invalid property
  14 : 120, //<--- invalid property
}

尝试使用 Partial 使所有键都可选:

type rate = 60 | 30 | 20 | 15 | 12 | 10 | 6 | 5 | 4 | 3 | 2 | 1;

const d2: Partial<Record<rate, number>> = {
  60: 100,
  20: 150,
}; // no error!