typescript - 具有可选特定值的混合类型索引签名
问题描述
我有一个对象,它存储与其他对象相关的值,由它们的数字 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'
而不需要做任何事情?
解决方案
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
可选?
推荐阅读
- python - 开发回合制战斗游戏
- reactjs - 我如何使用 isLoading 状态测试 useEffect
- c++ - 在没有执行实际行的情况下触发 VisualStudio 断点
- zsh - zsh中具有相同名称的别名的制表符完成
- php - 考虑到当前时间,PHP 中的日期 +3 周
- javascript - 将视频 currentTime 保存在 localStorage 和 video load() 在函数内部不起作用
- javascript - 如何使用 map 的 reduce 转换对象数组?
- laravel - 未能将一些参考资料推送到“https://git.heroku.com/”
- python - 如果值不是基于三列组合的第一次出现,如何创建空值
- c# - 返回一个枚举值