UNPKG

2.05 kBTypeScriptView Raw
1/**
2Tries to find the type of a global with the given name.
3
4Limitations: 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```
8import type {FindGlobalType} from 'type-fest';
9
10declare global {
11 const foo: number; // let and const don't work
12 var bar: string; // var works
13}
14
15type FooType = FindGlobalType<'foo'> //=> never (let/const don't work)
16type BarType = FindGlobalType<'bar'> //=> string
17type OtherType = FindGlobalType<'other'> //=> never (no global named 'other')
18```
19
20@category Utilities
21*/
22export type FindGlobalType<Name extends string> = typeof globalThis extends Record<Name, infer T> ? T : never;
23
24/**
25Tries to find one or more types from their globally-defined constructors.
26
27Use-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```
33import type {FindGlobalInstanceType} from 'type-fest';
34
35class Point {
36 constructor(public x: number, public y: number) {}
37}
38
39type PointLike = Point | FindGlobalInstanceType<'DOMPoint'>;
40```
41
42@example
43```
44import type {FindGlobalInstanceType} from 'type-fest';
45
46declare 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
55type FindFoo = FindGlobalInstanceType<'Foo'>; // Doesn't work
56type FindBar = FindGlobalInstanceType<'Bar'>; // Works
57```
58
59@category Utilities
60*/
61export 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;