I wonder if it is possible to type JSON-strings in Typescript. I would like to have this as feature in the code editor to have (compile time) error checks and autocompletion. I'm not looking for runtime validation.
I thought of something like this (try it yourself with TS Playground ):
export type Json<ContainedType> = string;
export function decodeJson<ContainedType>(
json: Json<ContainedType>
): ContainedType {
return JSON.parse(json) as ContainedType;
}
export function encodeJson<ContainedType>(
value: ContainedType
): Json<ContainedType> {
return JSON.stringify(value) as Json<ContainedType>;
}
export type ExampleType = {
example: string;
};
const example: ExampleType = { example: 'value' };
// expected type is Json<ExampleType> but vs code shows string
const encodedExample = encodeJson(example);
// expected type is ExampleType but vs code shows unknown
const decodedExample = decodeJson(encodedExample);
Any ideas to get something like this working?
jsonTypeA = jsonTypeBwould fail at compilation time if you've personally typed them correctly.