首页 > 解决方案 > 如何使用 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>那么错误就会消失。

标签: javascripttypescript

解决方案


您应该使用交集而不是union

type Foo = Record<"date", string> & Record<Age | Salary | Height, number>

操场


** 我已将date类型更改为,string因为您正在为该字段分配字符串值


推荐阅读