I have a function that works a bit like a wrapper for dynamic import() syntax:
async importWrapper(url) {
return await import(url);
}
Is there a way I can make this function use a return type based on the value of the url parameter?
I tried:
async function importWrapper<T extends string>(url: T) : Promise<typeof import(T)> {
return await import(url);
}
but this gives an error:
Promise<typeof import(T)>
// ^^^--- TS1141 String literal expected
playground
It is not possible, at least as of TypeScript 4.6, to express "import types" of a form like import(T) or typeof import(T).
There is an open feature request at microsoft/TypeScript#44636 asking for support for something like this. It is currently marked as "Awaiting Feedback" which means they would like to see what the community thinks before considering adopting such a feature. So you might want to give the issue a 👍 and comment on your use case; specifically why you need this and why existing workarounds don't suffice.
In any case I wouldn't expect to see anything implemented soon, or maybe even ever. A comment by the dev lead for TS says that it would be a "heavy lift" to implement. Oh well!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With