Last active
March 25, 2020 21:35
-
-
Save colinhacks/d7e6fc046f6dd458f0adab9a0992fb5e to your computer and use it in GitHub Desktop.
Generic TypeScript function that infers the literal type of any primitive, object, or tuple (literal JSON type inference)
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
type Primitive = string | number | boolean | null | undefined; | |
type Compound<U extends Primitive = Primitive> = | |
| U | |
| { [name: string]: Compound<U> } | |
| [] | |
| [Compound<U>] | |
| [Compound<U>, ...Compound<U>[]]; | |
type Json<U extends Primitive> = U | Compound<U>; | |
// this function infers the EXACT type of the value passed into it | |
// and returns it as a const will full type information | |
const inferLiteral = <U extends Primitive,T extends Json<U>>(arg: T): T => { | |
return arg; | |
}; | |
// equivalent to using "as const"; | |
const whatever = inferLiteral("whatever"); | |
const whatever = "whatever" as const; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment