Skip to content

Consider annotations and compilation of .json files #2064

Closed
@NoelAbrahams

Description

@NoelAbrahams

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    
}

Metadata

Metadata

Assignees

Labels

Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions