简体   繁体   中英

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

I have some json strings like this:

{
    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

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.

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. 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"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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