Created
December 18, 2020 11:05
-
-
Save ankon/14e823e3eed7cf353b6cd8ca8218ce7c to your computer and use it in GitHub Desktop.
JSON schema to TypeScript type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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