Description
Motivation
The shape of JSON stored in files can be validated using JSON schema. However, JSON schema cannot be used to ensure the stored JSON corresponds to a specific TypeScript interface.
Understandably, most JSON tends to be stored in databases. However, there are many cases where small documents are stored on the file system in order to permit quick editing. Two common examples are config and resource files. The JSON in these files is loaded at runtime and accessed by JavaScript code, thereby necessitating they correspond to specific TypeScript interfaces.
We have a small but significant use case for this scenario.
Proposal
Interface declarations file user.d.ts
declare module user {
interface Address {
house: number;
street: string;
}
interface User {
name: string;
address:Address;
age: number;
}
}
TypeScript JSON file user.json.ts
/// <reference path="user.d.ts" />
user.User: { <----------- Annotation
"name": "Joe Bloggs", /*Comment*/ // Permit comments
"address": {
"house": "1", // Error: Number expected
street: "London" // Error: Names must be quoted
},
"age": 55 // Error: Missing comma
"id": 101 // Error: Invalid property
}
Compiled output (after errors are corrected): File user.json
{
"name": "Joe Bloggs",
"address": {
"house": 1
"street": "London"
},
"age": 55
}