Skip to content

Instantly share code, notes, and snippets.

@colinhacks
Last active March 25, 2020 21:35
Show Gist options
  • Save colinhacks/d7e6fc046f6dd458f0adab9a0992fb5e to your computer and use it in GitHub Desktop.
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)
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