Open
Description
Search Terms
- JSON
Suggestion
Type annotation for JSON in a string.
Use Cases
Let's say you have a string which contains valid JSON object, like so:
const json = '{"hello": "world"}';
How can you type annotate the json
variable? Currently, you can mark it as a string
:
const json: string = '{"hello": "world"}';
Instead there could be some TypeScript language feature that helps with typing JSON in a string more precisely, for example:
const json: JSON {hello: string} = '{"hello": "world"}';
Examples
Specify that string contains valid JSON.
let json: JSON any;
let json: JSON; // shorthand
Add typings to an HTTP response body.
let responseBody: JSON {ping: 'pong'} = '{"ping": "pong"}';
Add type safety to JSON.parse()
method.
let responseBody: JSON {ping: 'pong'} = '{"ping": "pong"}';
let {ping} = JSON.parse(responseBody);
typeof ping // 'pong'
JSON cannot contain complex types.
type Stats = JSON {mtime: Date}; // Error: Date is not a valid JSON type.
Doubly serialized JSON.
let response: JSON {body: string} = '{"body": "{\"userId\": 123}"}';
let fetchUserResponse: JSON {body: JSON {userId: number}} = response;
Get type of serialized JSON string using jsontype
keyword.
type Response = JSON {body: string, headers: object};
type ResponseJson = jsontype Response; // {body: string, headers: object}
type ResponseBody = ResponseJson['body']; // string
type ResponseBody = (jsontype Response)['body']; // string
Specify that variable is JSON-serializable.
let serializable: jsontype JSON = {hello: 'world'};
JSON.serialize(serializable); // OK
let nonserializable: object = {hello: 'world'};
JSON.serialize(nonserializable); // Error: 'nonserializable' might not be serializable.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript / JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. new expression-level syntax)
Syntax Alternatives
type ResponseRaw = JSON {ping: 'pong'};
type ResponseRaw = json {ping: 'pong'};
type ResponseRaw = string {ping: 'pong'};
type ResponseRaw = json_string {ping: 'pong'};
type ResponseRaw = JSON<{ping: 'pong'}>;
type ResponseRaw = JSON({ping: 'pong'});
type Response = jsontype Response; // {ping: 'pong'}
type Response = typeof Response; // {ping: 'pong'}
type Response = parsed(Response); // {ping: 'pong'}