首页 > 解决方案 > 值必须是对象中的键

问题描述

想要强制值指向这样的类型的键,不知道如何最好地做到这一点

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

没运气

标签: typescripttypescript-typings

解决方案


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

希望有帮助。祝你好运!

链接到代码


推荐阅读