Skip to content

Instantly share code, notes, and snippets.

@BenoitZugmeyer
Last active May 28, 2020 08:06
Show Gist options
  • Save BenoitZugmeyer/fe9eeea66b41a1e1883fdf6d472c39a3 to your computer and use it in GitHub Desktop.
Save BenoitZugmeyer/fe9eeea66b41a1e1883fdf6d472c39a3 to your computer and use it in GitHub Desktop.
type TypeOfSchema<T extends any> =
T extends { type: "null" } ?
null :
T extends { type: "boolean" } ?
boolean :
T extends { type: "object" } ?
{ [K in keyof T["properties"]]: TypeOfSchema<T["properties"][K]> } :
T extends { type: "array" } ?
T extends { items: infer U } ?
{ foo: TypeOfSchema<U>[] } :
[] :
T extends { type: "number" } ?
number :
T extends { type: "string" } ?
string :
T extends { const: infer U } ?
U :
T extends { anyOf: (infer U)[] } ?
{ foo: TypeOfSchema<U> } :
never
// "null", "boolean", "object", "array", "number", or "string"
const schema = {
type: "object",
properties: {
foo: {
type: "string" as "string"
},
bar: {
const: "bar" as "bar"
},
biz: {
type: "array" as "array",
items: { type: "string" as "string" },
},
baz: {
anyOf: [{ const: "bar" as "bar" }, { const: "baz" as "baz" }]
}
},
}
type Hop = TypeOfSchema<typeof schema>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment