Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
Typescript: object with classes as a values

Let's say I want to build a proxy class from this question's accepted answer.

So I need to prepare some object which contains all the classes as values:

class Class1 {}
class Class2 {}

const ClassEnumeration = {
  class1: Class1,
  class2: Class2
}

// then it will be used like that
class DynamicClass {
    constructor (className, opts) {
        return new classes[className](opts);
    }
}

new DynamicClass('Class1');
new DynamicClass('Class2');

I can't get which type ClassEnumeration has in this case. I guess it will be something like Record<string, ...?? > Which type has the second argument here?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should define it like this:

const classes: Record<string, { new(...args: any[]): any }> = {
  class1: Class1,
  class2: Class2
}

Be aware that I used ...args: any[] as the constructor parameters since you did not define how the constructor parameters should look like. Right now it will accept any arguments.

Also the constructor will currently not work like that. You need to make opts optional and declare the types.

class DynamicClass {
    constructor (className: string, opts?: any) {
        return new classes[className](opts);
    }
}

Playground

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!