简体   繁体   English

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

[英]How to define a type for a json with nested properties in typescript?

I have some json strings like this: 我有一些像这样的json字符串:

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

I want to make it typed, so I define a type like this: 我想输入它,所以我定义了一个这样的类型:

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

Unfortunately, the syntax is not correct. 不幸的是,语法不正确。 it reports: 它报告:

Unexpected token n in JSON at position 15 JSON中位置15处的意外令牌n

I'm not familiar with typescript, and I just want to try if it's possible to define types like this, to put type definitions nested together and has almost same shape as the actual json. 我对Typescript不熟悉,我只想尝试是否可以定义这样的类型,将类型定义嵌套在一起,并且形状与实际json几乎相同。

Is it possible? 可能吗? And what's the correct way to define it? 定义它的正确方法是什么?

The type definition looks fine. 类型定义看起来不错。 The problem is that your JSON is not correctly formatted. 问题是您的JSON格式不正确。 It needs to use double quotes on the property names and string values: 它需要在属性名称和字符串值上使用双引号:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM