我有以下我无法控制的 JSON:
{
"date": "2020-01-01T00:00:00",
"a": 0,
"b": 0,
"c": 0
}
而不是指定接口(interface):
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;
Element implicitly has 'any' type.
如果我删除 Record<Age | Salary | Height, number>
然后错误就消失了。
最佳答案
您应该使用intersection而不是union :
type Foo = Record<"date", string> & Record<Age | Salary | Height, number>
<小时/>
** 我已将 date
类型更改为 string
,因为您要为此字段分配字符串值
关于javascript - 如何使用 Typescript 通过类型而不是接口(interface)来建模对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61187226/