简体   繁体   中英

enforce type of Object's Key

I'm trying to make a dictionary object that can have only certain keys.

I want to limit the keys to the 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
}

I tried the following and works to detect wrong types such as 11 , but it forces the Object to have all the keys which is something i don't want.

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

I need a type that allows this:

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

and not this:

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

Try using Partial which makes all keys optional:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM