Skip to content

Instantly share code, notes, and snippets.

@chuckadams
Last active September 13, 2020 17:52
Show Gist options
  • Save chuckadams/99f11a0ea11a620dd46b03fb5eb37967 to your computer and use it in GitHub Desktop.
Save chuckadams/99f11a0ea11a620dd46b03fb5eb37967 to your computer and use it in GitHub Desktop.
Stupid Typescript tricks
//// Exact types
type Exact<TExpected, TActual extends TExpected> = TExpected extends TActual ? TExpected: never;
type Foo = { x: number };
function acceptT<T extends Foo>(input: Exact<Foo, T>) {}
//// JSON Schema Type
type JSONSchema<T> = T extends number
? {
type: "number" | "integer"
[keyword: string]: any
}
: T extends string
? {
type: "string"
[keyword: string]: any
}
: T extends boolean
? {
type: "boolean"
}
: T extends undefined | null
? {
type: "null"
}
: T extends any[]
? {
type: "array"
items: JSONSchema<T[0]>
[keyword: string]: any
}
: {
type: "object"
properties: {
[P in keyof T]: JSONSchema<T[P]>
}
required: (keyof T)[]
[keyword: string]: any
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment