首页 > 解决方案 > 具有可选特定值的混合类型索引签名

问题描述

我有一个对象,它存储与其他对象相关的值,由它们的数字 id 键控。

const values = {
  1: 0.5, // id 1
  2: 0.8, // id 2
}

然而,还有一个带有字符串 id 的特殊异常键'all',因此对象可能如下所示:

const values = {
  'all': 0.3,
  1: 0.5,
  2: 0.8,
}

我已经创建了type ObjectId = number | 'all'可以很好地在我的应用程序周围传递混合类型 id 的方法,但是在键入上述值对象的索引签名中不能正常工作。如果我做我在其他地方看到的混合类型索引签名:

type ObjectId = number | 'all';

interface Values {
  [id in ObjectId]: number;
}

编译为

interface Values {
  [id: number]: number;
  'all': number;
}

这使得该'all'属性成为必需,因此像我的第一个示例这样的对象会引发类型错误。

我怎样才能为这个对象编写一个接口来限制键numbers or the string 'all'而不需要做任何事情?

标签: typescript

解决方案


interface Values {
  [id: number]: number;
  'all'?: number;
}

function foo(value: Values) {}

foo({
  1: 1,
});
foo({
  all: 1,
});
foo({
  1: 1,
  all: 1,
  other: 2, // will raise an error
});

使all可选?


推荐阅读