值必须是对象中键的keyof

时间:2019-09-24 22:12:02

标签: typescript typescript-typings

想要强制值指向这样的类型的键,不确定如何做到最好

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>
}

没有运气

1 个答案:

答案 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'
});

希望有帮助。祝你好运!

Link to code

相关问题