Skip to content

Instantly share code, notes, and snippets.

@ankon
Created December 18, 2020 11:05
Show Gist options
  • Save ankon/14e823e3eed7cf353b6cd8ca8218ce7c to your computer and use it in GitHub Desktop.
Save ankon/14e823e3eed7cf353b6cd8ca8218ce7c to your computer and use it in GitHub Desktop.
JSON schema to TypeScript type
interface SchemaTypeNames {
'string': string;
'boolean': boolean;
'number': number;
// TODO: Could we recurse for 'array' and 'object'?
'array': any[];
'object': unknown;
}
type Schema = {required?: any[], properties: Record<string, any>};
type NotIncluded<T, U> = T extends U ? never : T;
type Included<T, U> = T extends U ? T : never;
type RequiredParameters<S extends Schema> = {
[k in Included<keyof S['properties'], S['required'][number]>]: SchemaTypeNames[S['properties'][k]["type"]];
}
type NotRequiredParameters<S extends Schema> = {
[k in NotIncluded<keyof S['properties'], S['required'][number]>]?: SchemaTypeNames[S['properties'][k]["type"]];
}
/**
* Type created from a JSON schema definition
*
* Note that the `required` and `type` values must be constants (i.e. either the schema is loaded from a file, or the
* `as const` syntax is used for these)
*/
export type SchemaType<S extends Schema> = RequiredParameters<S> & NotRequiredParameters<S>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment