简体   繁体   English

强制对象键的类型

[英]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

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.我尝试了以下方法并努力检测错误类型,例如11 ,但它强制 Object 拥有所有我不想要的键。

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:尝试使用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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Typescript-实施对象键类型的更好方法? - Typescript - Better way to enforce an object's key type? 如何强制执行 object 值以匹配 object 键? - How to type-enforce object value to match object key? 您可以在对象上强制执行键,但让打字稿推断出Value的类型吗? - Can you enforce a key on an object but let typescript deduce the type of Value? 如何将 object 的密钥强制为某种类型? - How do I enforce a key of an object to be of a certain type? 在结构化对象中强制类型 - Enforce type in structured object 如何在 Typescript 中强制执行对象方法的显式返回类型? - How to enforce explicit return type of object's methods in Typescript? 根据 object 中另一个键的值强制执行特定类型的键(可区分联合) - Enforce a specific type of a key based on the value of another key in the object (Discriminated unions) 是否可以在不为其键显式设置类型的情况下强制执行对象值的类型? - Is it possible to enforce the type of an object's values without explicitly setting a type for its keys? 强制 object 包含枚举的所有键,并且仍然对其值进行类型推断 - Enforce object to contain all keys of an enum and still have type inference for it's values 在反应打字稿中声明对象的键类型 - Declaring object's key type in react typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM