想要强制值指向这样的类型的键,不确定如何做到最好
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>
}
没有运气
答案 0 :(得分:1)
TypeScript不能真正将Graph
表示为具体类型。但是,可以将其表示为generic类型,其中数字键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'
});
希望有帮助。祝你好运!