0

I'm trying to build a sort of model Factory in Typescript. I'm receiving a string parameter from an API call and I would like to istantiate a new object depending on the received value.

Here you can find a simple example of what I would like to accomplish:

/classes/ClassA.ts

export class ClassA {
  doSomething() {
    console.log("ClassA");
  }
}

/classes/ClassB.ts

export class ClassB {
  doSomething() {
    console.log("ClassB");
  }
}

/classes/index.ts

import { ClassA } from './ClassA';
import { ClassB } from './ClassB';
export { ClassA, ClassB }

Now, I would like to import all classes exported from index.ts (this file will be automatically updated when a new Class is being created) and run doSomething() on a class depending on a variable value:

/index.ts

import * as Classes from './classes';

const className: string = "ClassA";
new Classes[className]().doSomething()

In visualStudioCode I don't get any error, but at compile time I get:

error TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'typeof import("/testApp/src/tmp/classes/index")'.

Even changing className to "any" gives the same result.

If I remove className type

const className = "ClassA";

it works without any issue but I cannot proceed in this direction because received value is "typed" as string. I know that prepending istantiation code with

// @ts-ignore

It works but I would like to avoid this kind of "tricks" So, what would it be the correct way to type className getting it's possible values from the imported ts?

Thanks Micko

Micko
  • 41
  • 1
  • 5
  • 2
    Try setting the `className` to `keyof typeof Classes` type, instead of `string` type: `const className: keyof typeof Classes = "ClassA";` – Kapobajza Sep 22 '21 at 17:26
  • Thanks sir, I think that I tried all possible combinations of keyof / typeof missing yours.. It's working now – Micko Sep 22 '21 at 21:52

0 Answers0