Last active
April 13, 2021 03:22
-
-
Save jereddanielson/8bcfba0c081d13cd2b29ab951e673d45 to your computer and use it in GitHub Desktop.
This utility type will extract the schema properties definition from a valid JSONSchema7 object into a 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
import { JSONSchema7 } from 'json-schema'; | |
type StringToType = { | |
string: string; | |
boolean: boolean; | |
number: number; | |
integer: number; | |
null: null; | |
object: object; | |
array: object; | |
}; | |
type StringToTypeIndex<Property> = Property extends keyof StringToType | |
? StringToType[Property] | |
: never; | |
type ValidateIsJSONSchema7<Schema> = Schema extends JSONSchema7 | |
? Schema | |
: never; | |
export type ExtractProperties< | |
Schema extends JSONSchema7 | |
> = Schema['type'] extends 'object' | |
? { | |
[Property in keyof Schema['properties']]: ExtractProperties< | |
ValidateIsJSONSchema7<Schema['properties'][Property]> | |
>; | |
} | |
: Schema['type'] extends 'array' | |
? Array<ExtractProperties<ValidateIsJSONSchema7<Schema['items']>>> | |
: StringToTypeIndex<Schema['type']>; | |
// Example | |
const foo = { | |
properties: { | |
foo: { | |
type: 'object' as const, | |
properties: { | |
baz: { | |
type: 'boolean' as const, | |
}, | |
}, | |
}, | |
bar: { type: 'string' as const }, | |
}, | |
}; | |
type Foo = ExtractProperties<typeof foo>; | |
/** | |
* typeof Foo = { | |
* foo: { | |
* baz: boolean; | |
* }, | |
* bar: string; | |
* } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment