Home > Net >  Typescript: object with classes as a values
Typescript: object with classes as a values

Time:05-14

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?

CodePudding user response:

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

  • Related