首页 > 解决方案 > 显式指定静态字典值类型,同时推断确切的形状(或至少键)

问题描述

我想创建一个静态字典,作为单个对象文字,我会

  1. 明确指定值的类型,所以我得到类型检查和 IDE 建议
  2. 仍然能够推断出确切的形状(或至少是键)

我知道我可以通过简单地输入 dict 在真空中实现第一部分:

type Item = { id: number, description: string }
const staticDict: Partial<Record<string, Item>> = {
  first: { id: 1, description: "first" },
  second: { id: 2, description: "second" },
}

第二部分通过as const断言:

type Item = { id: number, description: string }
const StaticDict = {
  first: { id: 1, description: "first" },
  second: { id: 2, description: "second" },
} as const

但是我如何组合这些方法,同时仍将字典定义保留为单个文字(无需提前声明和输入)firstsecond

这实际上不起作用:

type Item = { id: number, description: string }
const staticDict: Partial<Record<string, Item>> = {
  first: { id: 1, description: "first" },
  second: { id: 2, description: "second" }, 
} as const
type Keys = keyof typeof StaticDict // results in `string`, I want "first" | "second"

而且我不想断言每个 item as Item,因为这种方法不会阻止我指定未知属性。我还有其他选择吗?

标签: typescriptdictionary

解决方案


至少获得类型检查的解决方法不是扩大类型staticDict,而是稍后将其分配给更广泛的类型以检查其形状是否正确。您可以将其作为块中的 const 执行,根据定义,该块在单行之外不可见。这可能会使它的意图更清晰(例如,它是一张支票,没有在其他任何地方使用)。

对于您的情况,可能会有更好的语法糖(例如,如果它们很多,请将它们分配给类型化数组)。

type Item = { id: number, description: string }
const staticDict = {
  first: { id: 1, description: "first" },
  second: { id: 2, description: "second" },
  third: "incorrect"
} as const;
{
    //correctly reports error
    const checkDict: Partial<Record<string, Item>> = staticDict;
}
//correctly infers keys
type Keys = keyof typeof staticDict;

推荐阅读