Last active
September 13, 2020 17:52
-
-
Save chuckadams/99f11a0ea11a620dd46b03fb5eb37967 to your computer and use it in GitHub Desktop.
Stupid Typescript tricks
This file contains 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
//// 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