我正在try 创建只能具有特定键的dictionary对象.
我想把 keys 限制在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
}
我try 了以下方法并try 检测错误的类型,例如11
,但它强制对象拥有all个键,这是我不想要的.
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
}