'What's the return type of a dynamic import?
I have a file, which must be loaded asynchronously, so I made a function, which loads this file and returns the Promise:
export function load() {
// ...
return import(filename);
}
What is the return type of this Function? Promise<any> works, but it feels very weird. I'd like to write the signature as.
export function load() -> Promise<???>;
Solution 1:[1]
With latest React, the dynamic import types are:
type DynamicImportType = () => Promise<{ default: React.ComponentType<any>; }>;
type LazyComponentType = React.LazyExoticComponent<React.ComponentType<any>>;
const dynamicImport: DynamicImportType = () => import('./MyComponent');
const LazyComponent: LazyComponentType = React.lazy(dynamicImport);
Resources
React.lazy- dynamic imports
- Search for "
LazyExoticComponent" in the React types
Solution 2:[2]
counter.ts:
export class Counter {}
export const list = ['test'];
index.ts:
type ImportClass<T, K extends keyof T> = T extends Record<K, infer S>
? S extends new (...args: any[]) => infer R
? R
: never
: never;
type ImportType<T, K extends keyof T> = T extends Record<K, infer R>
? R
: never;
type Counter = ImportClass<typeof import('./counter'), 'Counter'>;
type List = ImportType<typeof import('./counter'), 'list'>;
Solution 3:[3]
In my case I was able to just import as usual just the types, and dynamically import the actual classes etc I used.
For example,
I have a HttpModule.ts which uses import { ... } from "uWebSockets.js"
Even though it's in my internal library, I wasn't actually using the HttpModule.ts (but my library included it in the index.ts) I still got errors of the binaries uWebSockets.js where using is missing, in other words it's loaded the module.
This is because I had:
import uWS, {
HttpRequest as uWSHttpRequest,
HttpResponse as uWSHttpResponse,
RecognizedString,
us_socket_context_t
} from "uWebSockets.js";
Changing to just including the types:
import {
HttpRequest as uWSHttpRequest,
HttpResponse as uWSHttpResponse,
RecognizedString,
us_socket_context_t
} from "uWebSockets.js";
Skipped the file, when to initialize the actual uWS I did:
const app = (await import("uWebSockets.js")).App({});
Now, only when I'm actually using the HttpModule.ts it will import the uWebSockets.js module.
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 | Ian Campbell |
| Solution 2 | unadlib |
| Solution 3 | Ido |
