javascript - 如何使用 Typescript 通过类型而不是接口对对象进行建模?
问题描述
我有以下我无法控制的JSON :
{
"date": "2020-01-01T00:00:00",
"a": 0,
"b": 0,
"c": 0
}
而不是指定接口:
interface Foo {
date: Date,
"a": number,
"b": number,
"c": number
}
我希望能够像这样静态键入有效负载:
type Age = "a";
type Salary = "b";
type Height = "c"
type Foo = Record<"date", Date> | Record<Age | Salary | Height, number>;
即使编译器看起来很高兴,但是当我尝试从对象中获取日期时,我收到以下错误:
const foo = {
"date": "2020-01-01T00:00:00",
"a": 0,
"b": 0,
"c": 0
} as Foo;
元素隐含地具有“任何”类型。
如果我删除了,Record<Age | Salary | Height, number>
那么错误就会消失。
解决方案
推荐阅读
- python - 向 pandas 的 pivot_table 方法提供 lambda 函数列表时出现“仅对具有唯一值的索引对象有效的重新索引”错误?
- angular - 如何让 MsalGuard 使用我的客户端 ID?
- list - 如何将球拍方案列表添加在一起
- java - 解决“ValueError:文件意外结束。” 从 scipy/wavfile/读取
- r - 如何从 R 中的语料库中删除文本?
- wordpress - 如何修复 wordpress 中的响应式图像错误?
- python - 使用 psycopg2 获取具有键值的表中的值
- google-cloud-storage - 我可以手动触发 Google Cloud Storage 事件触发器吗?
- nginx - NGINX 无法加载站点
- r - 如何在 AKIMA 中使用 interp2xyz 修复插值中的缺失值