type ParserError = { error: true } & T; type EatWhitespace = string extends State ? ParserError<"EatWhitespace got generic string type"> : State extends ` ${infer State}` | `\n${infer State}` ? EatWhitespace : State; type AddKeyValue< Memo extends Record, Key extends string, Value extends any, > = Memo & { [K in Key]: Value }; type ParseJsonObject< State extends string, Memo extends Record = {}, > = string extends State ? ParserError<"ParseJsonObject got generic string type"> : EatWhitespace extends `}${infer State}` ? [Memo, State] : EatWhitespace extends `"${infer Key}"${infer State}` ? EatWhitespace extends `:${infer State}` ? ParseJsonValue extends [infer Value, `${infer State}`] ? EatWhitespace extends `,${infer State}` ? ParseJsonObject> : EatWhitespace extends `}${infer State}` ? [AddKeyValue, State] : ParserError<`ParseJsonObject received unexpected token: ${State}`> : ParserError<`ParseJsonValue returned unexpected value for: ${State}`> : ParserError<`ParseJsonObject received unexpected token: ${State}`> : ParserError<`ParseJsonObject received unexpected token: ${State}`>; type ParseJsonArray< State extends string, Memo extends any[] = [], > = string extends State ? ParserError<"ParseJsonArray got generic string type"> : EatWhitespace extends `]${infer State}` ? [Memo, State] : ParseJsonValue extends [infer Value, `${infer State}`] ? EatWhitespace extends `,${infer State}` ? ParseJsonArray, [...Memo, Value]> : EatWhitespace extends `]${infer State}` ? [[...Memo, Value], State] : ParserError<`ParseJsonArray received unexpected token: ${State}`> : ParserError<`ParseJsonValue returned unexpected value for: ${State}`>; type ParseJsonValue = string extends State ? ParserError<"ParseJsonValue got generic string type"> : EatWhitespace extends `null${infer State}` ? [null, State] : EatWhitespace extends `true${infer State}` ? [true, State] : EatWhitespace extends `false${infer State}` ? [false, State] : EatWhitespace extends `"${infer Value}"${infer State}` ? [Value, State] : EatWhitespace extends `[${infer State}` ? ParseJsonArray : EatWhitespace extends `{${infer State}` ? ParseJsonObject : ParserError<`ParseJsonValue received unexpected token: ${State}`>; export type ParseJson = ParseJsonValue extends infer Result ? Result extends [infer Value, string] ? Value : Result extends ParserError ? Result : ParserError<"ParseJsonValue returned unexpected Result"> : ParserError<"ParseJsonValue returned uninferrable Result">; type Person = ParseJson<'{ "name": "Jamie Kyle", "twitter": "https://twitter.com/buildsghost" }'>; // { // "name": "Jamie Kyle", // } & { // "twitter": "https://twitter.com/buildsghost" // } export default class Foo { person: Person; pooop: Poop; } export const person: Person = { name: "Jamie Kyle", twitter: "https://twitter.com/buildsghost", };