'Get keys of namespace and access namespace members with brackets
How can i import all types from a file without changing it, like the test.ts file below, and access them via the bracket syntax?
test.ts
export type TEST1 = 'test1'
export type TEST2 = 'test2'
export type TEST3 = 'test3'
export type TEST4 = 'test4'
index.ts
import type * as T from './test'
const a: T.TEST1 = 'test1' // what i can do
type B = 'TEST2' | 'TEST3' // subset of available types in test.ts
const b: T[B] = 'test2' // what i want to do
Solution 1:[1]
At first glance at the docs it may seem like this is not possible but I think I figured it out. For this specific scenario you've shown in your example where the types are string literals, you could use a combination of an indexable type and a mapped type like this:
test.ts
type TYPES = 'test1' | 'test2' | 'test3' | 'test4';
type MAPPED = {
[key in TYPES]: TYPES;
}
type TYPE = {
TEST1: 'test1',
TEST2: 'test2',
TEST3: 'test3',
TEST4: 'test4'
}
type T = MAPPED & TYPE;
export default T;
index.ts
import type T from './test';
type b = 'TEST2' | 'TEST3';
const b: T[b] = 'test1';
The second line will show the error:
Type '"test1"' is not assignable to type '"test2" | "test3"'. Did you mean '"test2"'?
Which proves that this is working as intended.
Solution 2:[2]
I would recommend you to use next/head I normally use this to put my scripts but it depends on your case, remember that using different strategies (like lazyOnload) and the order in some cases is important, but if you require to use next/script as the docs says then, check your strategies try with other ones like beforeInteractive and double check the order in which your scripts should be loaded and if you continue getting those errors probably the error is related with the content of your scripts, open your network tab and inspect what happened.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Alejandro Rodriguez |
