typescript - 显式指定静态字典值类型,同时推断确切的形状(或至少键)
问题描述
我想创建一个静态字典,作为单个对象文字,我会
- 明确指定值的类型,所以我得到类型检查和 IDE 建议
- 仍然能够推断出确切的形状(或至少是键)
我知道我可以通过简单地输入 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
但是我如何组合这些方法,同时仍将字典定义保留为单个文字(无需提前声明和输入)first
?second
这实际上不起作用:
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
,因为这种方法不会阻止我指定未知属性。我还有其他选择吗?
解决方案
至少获得类型检查的解决方法不是扩大类型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;
推荐阅读
- linux - 如何强制 malloc 在 64 位系统上返回像指针一样的 32 位?
- python - 函数返回更新值
- python - 使用 Pandas 从具有多个条件的文本文件中导入数据
- javascript - Babel 与 .babelrc 如何修复 MODULE_NOT_FOUND?
- c# - 分配新的 CancellationTokenSource() 是否有任何问题?对一个变量不止一次?
- git - 错误:远程解包失败:完全读取包头之前的 eof
- pandas - 如何将熊猫期间索引更改为小写?
- c# - C# XDocument - 获取 XML 文件中属性的值
- python - 如何使用 python/osx 在按键上退出循环?
- python - Tweepy:忽略以前的推文以改进优化