typescript - 值必须是对象中的键
问题描述
想要强制值指向这样的类型的键,不知道如何最好地做到这一点
type Graph = {
[nodeId: number]: Array<keyof Graph>
}
const graph: Graph = {
0: [1, 2, 3],
1: [2],
2: [3],
3: [1],
}
也试过
type Graph = {
[nodeId: number]: Array<nodeId>
}
没运气
解决方案
TypeScript 不能真正表示Graph
为具体类型。但是,可以将其表示为通用类型,其中数字键K
是类型的一部分:
type Graph<K extends number> = { [P in K]: K[] };
然后您可以使用辅助函数来推断K
给定值的正确值:
const asGraph = <K extends number, V extends K>(g: Record<K, V[]>): Graph<K> =>
g;
const goodGraph = asGraph({
0: [1, 2, 3],
1: [2],
2: [3],
3: [1]
}); // Graph<0 | 1 | 2 | 3>
它正确地拒绝了坏图:
const badKey = asGraph({
zero: [1], // error! "zero" does not exist in Record<number, number[]>
1: [1]
});
const badValue = asGraph({
0: [1],
1: [0],
2: [8675309], // error! number not assignable to '0 | 1 | 2'.
3: ["zero"] // error! string also not assignable to '0 | 1 | 2'
});
希望有帮助。祝你好运!
推荐阅读
- forms - 当使用其他表单输入时,如何阻止谷歌地图自动完成结果消失?
- java - 为什么 java Base64 运行与 eclipse 和 jar 不同
- rest - 如何使用 ureq 发布登录请求?
- r - 在 R 中不使用 PAM 创建自己的 k-medoids 算法?
- r - 为什么我的代码会得到不同的结果?
- python - Pandas groupby 分组返回值而不是索引
- css - 从底部到顶部css对图像的渐变效果
- python - 如何将用户定义的类从包导入到 Jupyter Notebook
- jq - 替换列表中的值
- .net-core - 从核心 2.1 升级后无法发布核心 3.1 独立应用程序,nuget 以某种方式失败?构建良好