1 | /**
|
2 | Tries to find the type of a global with the given name.
|
3 |
|
4 | Limitations: Due to peculiarities with the behavior of `globalThis`, "globally defined" only includes `var` declarations in `declare global` blocks, not `let` or `const` declarations.
|
5 |
|
6 | @example
|
7 | ```
|
8 | import type {FindGlobalType} from 'type-fest';
|
9 |
|
10 | declare global {
|
11 | const foo: number; // let and const don't work
|
12 | var bar: string; // var works
|
13 | }
|
14 |
|
15 | type FooType = FindGlobalType<'foo'> //=> never (let/const don't work)
|
16 | type BarType = FindGlobalType<'bar'> //=> string
|
17 | type OtherType = FindGlobalType<'other'> //=> never (no global named 'other')
|
18 | ```
|
19 |
|
20 | @category Utilities
|
21 | */
|
22 | export type FindGlobalType<Name extends string> = typeof globalThis extends Record<Name, infer T> ? T : never;
|
23 |
|
24 | /**
|
25 | Tries to find one or more types from their globally-defined constructors.
|
26 |
|
27 | Use-case: Conditionally referencing DOM types only when the DOM library present.
|
28 |
|
29 | *Limitations:* Due to peculiarities with the behavior of `globalThis`, "globally defined" has a narrow definition in this case. Declaring a class in a `declare global` block won't work, instead you must declare its type using an interface and declare its constructor as a `var` (*not* `let`/`const`) inside the `declare global` block.
|
30 |
|
31 | @example
|
32 | ```
|
33 | import type {FindGlobalInstanceType} from 'type-fest';
|
34 |
|
35 | class Point {
|
36 | constructor(public x: number, public y: number) {}
|
37 | }
|
38 |
|
39 | type PointLike = Point | FindGlobalInstanceType<'DOMPoint'>;
|
40 | ```
|
41 |
|
42 | @example
|
43 | ```
|
44 | import type {FindGlobalInstanceType} from 'type-fest';
|
45 |
|
46 | declare global {
|
47 | // Class syntax won't add the key to `globalThis`
|
48 | class Foo {}
|
49 |
|
50 | // interface + constructor style works
|
51 | interface Bar {}
|
52 | var Bar: new () => Bar; // Not let or const
|
53 | }
|
54 |
|
55 | type FindFoo = FindGlobalInstanceType<'Foo'>; // Doesn't work
|
56 | type FindBar = FindGlobalInstanceType<'Bar'>; // Works
|
57 | ```
|
58 |
|
59 | @category Utilities
|
60 | */
|
61 | export type FindGlobalInstanceType<Name extends string> =
|
62 | Name extends string
|
63 | ? typeof globalThis extends Record<Name, abstract new (...arguments: any[]) => infer T> ? T : never
|
64 | : never;
|