我正在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
}

推荐答案

try 使用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!

Typescript相关问答推荐

处理API响应中的日期对象

如何为ViewContainerRef加载的Angular组件实现CanDeactivate保护?

使用React处理Websocket数据

Typescript泛型类型:按其嵌套属性映射记录列表

对扩展某种类型的属性子集进行操作的函数

通配符路径与每条路径一起显示

返回具有递归属性的泛型类型的泛型函数

如何将定义模型(在Vue 3.4中)用于输入以外的其他用途

防止重复使用 Select 器重新渲染

保护函数调用,以便深度嵌套的对象具有必须与同级属性函数cargument的类型匹配的键

如何编辑切片器以使用CRUD调用函数?

TypeScrip-如何自动推断UNION变量的类型

如何创建一个将嵌套类属性的点表示法生成为字符串文字的类型?

如何从JWT Reaction中提取特定值

使用&reaction测试库&如何使用提供程序包装我的所有测试组件

Select 类型的子项

如何在Vue动态类的上下文中解释错误TS2345?

Typescript 从泛型推断类型

Typescript 确保通用对象不包含属性

基于可选参数的动态类型泛型类型