-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
union.d.ts
34 lines (32 loc) · 1.34 KB
/
union.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import type { Primitive } from "./primitive.d.ts";
/**
* Allows creating a union type by combining primitive types and literal types
* without sacrificing IDE's auto-completion for the literal part of the union.
*
* Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals.
*
* This type is a workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as it's not needed anymore.
*
* @example ```ts
* import type {LiteralUnion} from 'type-fest';
* // Before
* type Pet = 'dog' | 'cat' | string;
* const pet: Pet = '';
* // Start typing in your TypeScript-enabled IDE.
* // You **will not** get auto-completion for `dog` and `cat` literals.
* // After
*
* type Pet2 = LiteralUnion<'dog' | 'cat', string>;
* const pet: Pet2 = '';
* // You **will** get auto-completion for `dog` and `cat` literals.
* ```
*
* @category Type
*/
export type LiteralUnion<
LiteralType,
BaseType extends Primitive,
> = LiteralType | (BaseType & Record<never, never>);
export type StringLiteralUnion<S extends string> = `${S}` extends
`${infer Str extends string}` ? LiteralUnion<Str, string>
: never;