Tailored production method based on specific criteria

One of my challenges is to create a versatile factory method using typescript.

The main objective is to initialize a class based on its name using generics, instead of employing if/else or switch statements.

I am aiming for similar functionality as this example:

document.createElement("p");

createElement<K extends keyof HTMLElementTagNameMap>(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];

interface HTMLElementTagNameMap {
    "a": HTMLAnchorElement;
    "abbr": HTMLElement;
    "address": HTMLElement;
    "applet": HTMLAppletElement;
...
}

I encountered an obstacle when attempting to instantiate a class type:

class A {

  constructor(private name:string,private id:number){

  }
}

class B extends A{

}

class C extends A{

}



interface stringToClassMap{
  'A':A;
  'B':B;
  'C':C;
}

// Should return a new instance every time
const obj: stringToClassMap = {A:new A('x',123),B:new B('x',123),C:new C('x',123)}

function creator<K extends keyof stringToClassMap>(key:K): A{
  return new obj[key](); 
}

Thank you!

Answer №1

class Z {
  constructor(public x: string) {}
}

class D {
  constructor(private label: string, private number: number) {}
}

class E extends D {}

class F extends Z {}

type Constructor<U> = new (...params: any) => U;
interface ClassMap {
  D: Constructor<D>;
  E: Constructor<E>;
  F: Constructor<F>;
  Z: Constructor<Z>;
}
// Generate new instance each time
const item: ClassMap = {
  D: D,
  E: E,
  F: F,
  Z: Z
};

function generator<L extends keyof ClassMap>(
  index: L,
  ...properties: any
): ClassMap[L] extends Constructor<infer N> ? N : never {
  const Element = item[index];
  return new Element(...properties) as any;
}

const eObj = generator("D", "");
const fObj = generator("E", "");
const gObj = generator("F", "");
const zObj = generator("Z", "");

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

Dynamic Text Labels in Treemap Visualizations with Echarts

Is it possible to adjust the text size dynamically based on the size of a box in a treemap label? I haven't been able to find a way to do this in the documentation without hardcoding it. Click here for more information label: { fontSize: 16 ...

What is the equivalent of html script tags in Webpack 2?

I recently downloaded a new npm module that suggests including the following code in my project: <link href="node_modules/ng2-toastr/bundles/ng2-toastr.min.css" rel="stylesheet" /> <script src="node_modules/ng2-toastr/bundles/ng2-toastr.min.js"&g ...

Is it advisable to specify data types for my JSON data in TypeScript?

For the shopping application in my project, I am utilizing a JSON structure to categorize products as either hot or branded. However, I encountered an issue when trying to define a type for the entire JSON object labeled "full". Despite my attempts, it app ...

What are the steps to implement the `serialport` library in `deno`?

After tinkering with Deno to extract readings from an Arduino, I encountered a roadblock when it came to using the serialport library correctly. Here is what I attempted: According to a post, packages from pika.dev should work. However, when trying to use ...

The specified type 'ListRenderItem<IPhotos>' cannot be assigned to type 'ListRenderItem<unknown>'

Can someone assist with resolving this error I'm encountering: Type 'ListRenderItem<IPhotos>' is not assignable to type 'ListRenderItem<unknown> Here is the code snippet: import { Dimensions, Image, ListRenderItem, Pressabl ...

Here is a unique version: "Dealing with Node.js ES6 (ESM) Modules in TypeScript can be tricky, especially when the TypeScript Compiler (TSC) fails to emit the

I am facing an issue while transpiling my TypeScript project to JavaScript. I have set the project to resolve as an ES6 Module (ESM) by using the "module":"ES6" configuration, but the problem persists. This is the current setup in my ...

Error message: "Error encountered while building Next.js - ReferenceError: 'describe' is not defined"

I am facing difficulties achieving a successful next build without encountering the following error: > Build error occurred { ReferenceError: describe is not defined Although the dev server and tests execute smoothly, it appears that the jest global d ...

The JSONP request failed with an error stating: ReferenceError: document is not defined

My internship project involves developing a mobile application based on the website www.claroline.net using Nativescript and Angular 2. I have successfully implemented the login function, allowing users to sign in to the app. Next, I need to integrate not ...

Leverage context to facilitate communication between components operating at various levels of the system

I am currently working on the settings pages of my applications. Each page features a common SettingsLayout (parent component) that is displayed across all settings pages. One unique aspect of this layout is the presence of an ActionsBar, where the submit/ ...

Utilize JavaScript libraries in a TypeScript project

Looking to integrate a payment system called iyzico into my project. The iyzico payment library can be found here. However, there are no types available for it. How can I utilize this library in my Node.js TypeScript Express backend project? I attempted t ...

How can you utilize an injected service from inside a Class decorator in Typescript/NestJS?

Can an injected service be accessed from within a Class decorator? I aim to retrieve the service in the personalized constructor: function CustDec(constructor: Function) { var original = constructor; var f: any = function (...args) { // How can I ...

Using Conditional Types in Supabase Query results in the TypeScript error, "Type is incompatible with type 'never'."

Query I have encountered a TypeScript issue while working on a Next.js project with Supabase as the backend. To handle responses from Supabase queries, I created some helper types, but I'm stuck on resolving this problem. Helper Types Overview: Belo ...

Another return payload failing to retrieve the return value

I'm currently facing an issue where a function that should return a value is not being passed on to another function. Below is the code snippet in question: public _getProfileToUpdate() { return { corporateId: this.storeService.setStoreData().p ...

Transforming an object's type into an array of different types

Looking to create an array of types based on object properties: type T = { a: number | string; b: string | number; c: number; d: boolean; }; Desired Output: [number | string, string | number, number, boolean] Intending to use this as a ...

The function call with Ajax failed due to an error: TypeError - this.X is not a function

I am encountering an issue when trying to invoke the successLogin() function from within an Ajax code block using Typescript in an Ionic v3 project. The error message "this.successLogin() is not a function" keeps popping up. Can anyone provide guidance on ...

Converting JSON to string in Typescript is causing an error where type string cannot be assigned to type '{ .. }'

Here's the code snippet I'm working with: interface ISource extends IdModel { source_type_id: number; network_id: number; company_connection_id: number; feed_id: number; connection_id: number; feed_ids: number[]; name: string; tag ...

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

The variable 'selectedvalue' is being accessed before it has been initialized

I'm currently working on sharing the date between components using BehaviorSubject, but I'm encountering an error in the process. public data = new BehaviorSubject<any>(this.selectedValue); public sharedData = this.data.asObservable(); sele ...

Setting up WebPack for TypeScript with import functionality

A tutorial on webpack configuration for typescript typically demonstrates the following: const path = require('path'); module.exports = { ... } Is it more advantageous to utilize ES modules and configure it with import statements instead? Or is ...

Problem encountered in a simple Jest unit test - Unexpected identifier: _Object$defineProperty from babel-runtime

Struggling with a basic initial test in enzyme and Jest during unit testing. The "renders without crashing" test is failing, as depicted here: https://i.stack.imgur.com/5LvSG.png Tried various solutions like: "exclude": "/node_modules/" in tsconfig "t ...