Is it possible to incorporate types using a generic parameter during import?

I have a function that acts as a wrapper for the dynamic import() syntax:

async importWrapper(url) {
  return await import(url);
}

Is there a way to make this function determine the return type based on the value of the url parameter?

I attempted:

async function importWrapper<T extends string>(url: T) : Promise<typeof import(T)> {
    return await import(url);
}

but encountered an error:

Promise<typeof import(T)>
//                   ^^^--- TS1141 String literal expected

playground

Answer №1

As of the latest TypeScript version 4.6, there is currently no way to represent "import types" using syntax like import(T) or typeof import(T).

An open feature request has been submitted on microsoft/TypeScript#44636, seeking community feedback on potentially incorporating this functionality. It's noted as "Awaiting Feedback," indicating a decision will depend on user responses. Consider showing your support by giving a thumbs up and explaining your use case along with why existing methods are inadequate.

Realistically, the chances of this feature being implemented soon, if at all, seem slim. A response from TS developer suggests it would require significant effort to implement. Such is life!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing conflicting versions of React in a component library created with Webpack and Storybook

My goal is to create a React component library on top of MUI using Storybook and TypeScript. Since Storybook is based on Webpack (which includes SASS files), I'm utilizing Webpack to build the bundle because TSC can't compile those files. Subsequ ...

What is the best way to automatically refresh an observable every 30 seconds?

@Component({ selector: 'app-geo', templateUrl: <img mat-card-image [src]="profileUrl | async "> export class GeoComponent implements OnInit { date; profileUrl: Observable<string>; constructor(private tempService ...

Is there a way to programmatically add a timestamp to a form in Angular6?

Is there a way to automatically populate new forms with the current datetime value? this.editForm.patchValue({ id: chatRoom.id, creationDate: chatRoom.creationDate != null ? chatRoom.creationDate.format(DATE_TIME_FORMAT) : null, roo ...

We were unable to identify any Next.js version in your project. Please ensure that the `"next"` package is installed in either the "dependencies" or "devDependencies" section

My attempt to deploy a Next app using the Vercel CLI has hit a roadblock. After running vercel build with no errors, I proceeded to deploy with vercel deploy --prebuilt, which also went smoothly. However, when trying to move the project from the preview en ...

Encountering issues with vite build due to @types/react-router-dom package

I ran into an issue while developing my react app using Vite and TypeScript. Everything works fine when using Vite for development, but as soon as I switch to "tsc && vite build", I encounter numerous errors from @types/react-router-dom and @types/react-ro ...

Troubles with Node and TypeScript: inability to detect jQuery

I'm currently facing some challenges with node and typescript that are causing issues in my Visual Studio 2015 projects. In the solution, I have two projects named Web and WebAPI. Both projects have node.js installed, each with their own node_modules ...

Is it beneficial to disable and deactivate Validators in Angular?

Within our Angular framework, we've implemented a form with 10 fields. However, a new requirement has surfaced where certain individuals only require access to specific fields out of the existing 10. To accommodate this, our team is currently addressi ...

Exporting data in its original raw format using R

Currently facing an issue with my Access database file (.accdb) while working in R. To resolve compatibility issues, I had to switch to the 32-bit version of R for accessing and importing data from the database successfully. However, when attempting operat ...

Implementing the "$store" property within Vue components

Click here for a guide on how to type the $store property. Unfortunately, I've been encountering issues with it. In my Vue 2 project created using vue-cliI, I included a vuex.d.ts file in ./src directory but the $store property in my components still ...

Importing functions from a subdirectory dynamically using Python can help streamline your code

Struggling with dynamically importing functions from a module based on a parameter. My setup includes a handler function and a directory with files, each containing a single function I need to utilize. I tried using import_module from importlib, but haven& ...

Can you point me to the source of definition for Vue 2's ComponentDefinition and ComponentConstructor types?

I am struggling to add a dynamic Vue 2 component with correct typing in TypeScript. The documentation clearly mentions that the is attribute accepts values of type string | ComponentDefinition | ComponentConstructor, but I cannot locate these custom types ...

I am facing an issue with my interface - the variable designed to store boolean values

Something unusual happened with Typescript - I assigned a string value to a boolean variable, but no error was generated. I purposely triggered an error in order to observe how Typescript would react, only to find that it did not produce the expected erro ...

In Typescript, the use of an array as a class member is not defined

I'm having trouble adding an array as a class member in my Typescript code. When I try to access it in a certain function, I keep getting an error saying it's undefined. What am I doing wrong? .html <button id="storePersonBtn"> .ts exp ...

Checkbox selections persist when navigating between pages

I am currently working with Angular 9 and I have a list of checkboxes that need to default to true when displaying certain data. If one of these checkboxes is unchecked, it should trigger the display of specific information. The issue I am facing is that o ...

Error message: 'import not located' when using custom types in Vue 3 with Vite/Vitesse

I'm currently working on a Vue 3 project using Vitesse (which is based on Vite). I created a custom type called ProductData in my src/types.ts file. However, when I try to use this type in one of my pages, the page fails to load and I see multiple con ...

Issues with Imported Routes Not Functioning as Expected

I am currently working on implementing routing in my Angular 2 project. All the components are functioning properly, but I encounter an error when I include 'appRoutes' in the imports section of app.module.ts. An unexpected TypeError occurs: C ...

The concept of nesting partial types in Typescript

Struggling to type partial objects from GraphQL queries, especially with an object that looks like this... // TypeScript types interface Foo { bar: Bar } interface Bar { a: number, b: number } // GraphQL query foo { bar { a // 'b&a ...

Creating applications with Angular2 and TypeScript is possible even without utilizing NPM for development

I've seen all the guides recommend installing npm, but I'm determined to find an alternative method. I found Angular2 files available here, however, none of them are in TypeScript code. What is the best course of action? Do I need Angular2.ts, ...

Angular2: Once user is authenticated, navigate to specific routes

I've developed an admin panel with a router for page navigation. The layout of the admin panel includes a sidebar (Component), header (Component), and content (Component). Within the content, I have inserted <router-outlet></router-outlet> ...

The element is implicitly assigned an 'any' type as the expression of type 'string' is unable to be used as an index within the type '{...}'

Trying to improve my react app with TypeScript, but encountering issues when typing certain variables. Here's the error message I'm facing: TypeScript error in /Users/SignUpFields.tsx(66,9): Element implicitly has an 'any' type becaus ...