UNPKG

899 BTypeScriptView Raw
1/**
2Given a [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) return the {@link Primitive | primitive type} it belongs to, or `never` if it's not a primitive.
3
4Use-case: Working with generic types that may be literal types.
5
6@example
7```
8import type {LiteralToPrimitive} from 'type-fest';
9
10// No overloads needed to get the correct return type
11function plus<T extends number | bigint | string>(x: T, y: T): LiteralToPrimitive<T> {
12 return x + (y as any);
13}
14
15plus('a', 'b'); // string
16plus(1, 2); // number
17plus(1n, 2n); // bigint
18```
19
20@category Type
21*/
22export type LiteralToPrimitive<T> = T extends number
23 ? number
24 : T extends bigint
25 ? bigint
26 : T extends string
27 ? string
28 : T extends boolean
29 ? boolean
30 : T extends symbol
31 ? symbol
32 : T extends null
33 ? null
34 : T extends undefined
35 ? undefined
36 : never;