Retrieve access type, path, and value when importing dynamically

I am seeking a solution to specify the argument for example. Currently, the code only sets it to any. Playground

function clientImport <T extends string>(v: T) {
  const resolve = () => import(v)
  type ResolveReturn = Awaited<ReturnType<typeof resolve>>
  const example = (value: ResolveReturn) => {
    return value
  }
  return {
    path: v,
    resolve,
    example
  }
}

const example = async () => {
    const { path, resolve, example } = clientImport('./client_code.tsx')
    console.log(path)
    const v = await resolve()
    //    ^?
    example(v)
    //  ^?
}

I am looking to type this as follows:

function clientImport <T extends string>(v: T) {
  return function <Z>(x: (q: T) => Promise<Z>) {
    return {
      resolve: () => x(v),
      path: v
    }
  }
}


const v = await clientImport('../examples/client_code/example.ts')(p => import(p))

Answer №1

By utilizing a build-step similar to Prisma, it is possible to automatically generate a function:

function _generateCode <T>(
  path: string,
  code: () => Promise<T>
) {
  return { path, code }
}

// This function would be automatically generated
const generatedFunctions = {
  '../examples/client_code/example.ts': _generateCode(
    import.meta.resolve('../examples/client_code/example.ts'),
    () => import('../examples/client_code/example.ts')
  )
}

function executeFunction (key: keyof typeof generatedFunctions) {
  return generatedFunctions[key]
}

const result = executeFunction('../examples/client_code/example.ts')

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

Is it possible to minimize the number of accessors needed for reactive forms?

Currently, I am dealing with a reactive form that consists of 20 different inputs. An example of one input is shown below: <input formControlName="name" matInput> For each input, I find myself needing to write an accessor function like the ...

Using {angular} import from 'angular' is causing a malfunction in AngularJS version 1.5

React - 17.0 TypeScript - 4.1.2 Babel - 7.13.14 tsconfig.json { "compilerOptions": { "target": "es6", "module": "esnext", "moduleResolution": "node", "jsx": ...

How can type annotations be properly incorporated into this TypeScript code using an inline function class?

How can I provide type annotations to inform TypeScript that this code is correct? Indeed, I do require that inline function class. The code presented here is a simplified version of my actual problem. let x = 10; const obj = new (function() { if(--x) r ...

Require using .toString() method on an object during automatic conversion to a string

I'm interested in automating the process of utilizing an object's toString() method when it is implicitly converted to a string. Let's consider this example class: class Dog { name: string; constructor(name: string) { this.name = na ...

Testing the addition of a dynamic class to an HTML button using Jasmine unit tests

I am brand new to Jasmine and currently in the process of grasping how to write Unit tests for my components in Angular 4. One issue I encountered is when I attempt to add a class to the button's classList within the ngOnInit() lifecycle hook of the C ...

Navigating through the child elements of a parent element in Aurelia

I am currently using Aurelia 1 to construct my application. Right now, I am in the process of creating a custom toolbar element known as custom-toolbar.ts. Within this toolbar, there will be an unspecified number of child elements referred to as custom-too ...

The ValidationPipe does not function properly when utilizing app.useGlobalPipes

Hello! I'm looking to implement the ValidationPipe globally using useGlobalPipes. Currently, my code looks like this: import 'dotenv/config'; import {NestFactory} from '@nestjs/core'; import {ValidationPipe} from '@nestjs/com ...

Utilizing Async/Await with Node.js for Seamless MySQL Integration

I have encountered two main issues. Implementing Async/Await in database queries Handling environment variables in pool configurations I am currently using TypeScript with Node.js and Express, and I have installed promise-mysql. However, I am open to usi ...

"Is there a way to dynamically remap an array only when there are changes

One of the challenges I am facing is with a component called Page, which contains two components - Editor and Preview. Page has an array called items. [ { value: 0, text: 'Item 1' }, ... ] This array items is passed ...

How to access elements by their class name in Angular

Recently, I encountered a situation with this specific span element: <span *ngFor="let list of lists[0].question; let i = index" id="word{{ i }}" (click)="changestyle($event)" class="highlight"> {{ list}} < ...

What could be the reason for certain Angular modules importing successfully while others fail to do so?

I am encountering an issue with a module that I am struggling to import. Using Typescript 2.7 and Node 10 The pxl-ng-security module is showing an error in both VSCode and VS2019. When hovering over it, error 2307 is displayed. Below is the import secti ...

Is there a method to retrieve Mui state classes easily?

One thing I really appreciate is the way to style mui-components with their class names. I'm curious if there's a method to access state classes like Mui-checked using a variable. Let me delve deeper into this: I have a styled component that lo ...

What is the significance of var-less variables in TypeScript class definitions?

Why is it that when creating a component class in Angular2, we don't need to use var when declaring a new variable? For example: @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> ` }) export class AppCo ...

The shape-matching subset functionality in Typescript is experiencing issues

One of the key principles of TypeScript is that type checking focuses on the structure of values, a concept known as duck typing or structural typing. This means that only a subset of an object's fields needs to match for it to be considered compatibl ...

Access an array to filter by specific key-value pairs

How can I efficiently filter an array using key and value pairs from within nested arrays? I am in need of a method to filter the elements of an array based on specific key-value pairs nested within another array. The key will always contain boolean value ...

Tips for selecting the correct type for an array of Unions with the help of Array.prototype.find

I have the following variations: type First = { kind: 'First', name: string } type Second = { kind: 'Second', title: string } type Combo = First | Second; I am attempting to locate the element of type First in a Combo[], as shown bel ...

Angular: Incorporating a custom validation function into the controller - Techniques for accessing the 'this' keyword

I'm currently working on implementing a custom validator for a form in Angular. I've encountered an issue where I am unable to access the controller's this within the validator function. This is the validator function that's causing tr ...

How to access a variable from outside a promise block in Angular

Is there a way to access a variable declared outside of a promise block within an Angular 6 component? Consider the following scenario: items: string[] = []; ngOnInit() { const url='SOME URL'; const promise = this.apiService.post(url ...

Having trouble sending correct true/false values for selected radio buttons on an Angular5 table, often requiring users to click them twice to submit the appropriate values

My goal is to assign true or false values to selected radio buttons in each row and then form an object for submission. To distinguish between the radio button values in each row, I have used {{k}}+{{sizeobj.rbSelected}} as the value which is causing issue ...

Guide on inputting Vue component in props

<template> <v-dialog width="auto" v-model="isShown" transition="dialog-bottom-transition" > <v-card> <v-card-title v-if="title"> {{ title }}</v-card-title> ...