如何在打字稿中为带有嵌套属性的json定义类型?

时间:2018-08-04 14:15:30

标签: json typescript types

我有一些像这样的json字符串:

{
    name: 'test',
    url: 'http://test.org',
    contact: {
        email: 'aaa@test.com',
        address: 'ab road'
    }
}

我想输入它,所以我定义了这样的类型:

type Site = {
    name: String,
    url: String,
    contact: {
        email: String,
        address: String
    }
};

不幸的是,语法不正确。它报告:

  

JSON中位置15处的意外令牌

我对typescript不熟悉,我只想尝试是否可以定义这样的类型,将类型定义嵌套在一起,并且形状与实际json几乎相同。

有可能吗?定义它的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

类型定义看起来不错。问题是您的JSON格式不正确。它需要在属性名称和字符串值上使用双引号:

{
    "name": "test",
    "url": "http://test.org",
    "contact": {
        "email": "aaa@test.com",
        "address": "ab road"
    }
}
相关问题