4

I tried to get to work some sort of:

export class SomeComponent {

  constructor() {

    let className: string = "TheClass";

    /* should be the same as .. = new TheClass() */
    let superSpecial = new className();

  }

}

I have not yet figured out how to do this? Could anyone help me?

3
  • Be aware that you can't just do this out of the box. You'll need to store your classes in a collection of some sort and then reference them. Commented Mar 26, 2017 at 23:21
  • This is more of a javascript question see stackoverflow.com/questions/9803947/create-object-from-string Commented Mar 26, 2017 at 23:22
  • What you are looking for is a "factory"; google for that. Commented Mar 27, 2017 at 2:08

3 Answers 3

5

There are a few ways to do this. If your class is in a separate module:

SomeClass.ts

export class SomeClass {

    constructor(arg: string) {
        console.log(arg);
    }
}

App.ts

import * as s from "./SomeClass";

var instance = new s["SomeClass"]("param");

Or using namespaces:

namespace Test {

    export class SomeClass {

        constructor(arg: string) {
            console.log(arg);
        }
    }
}

var instance = new Test["SomeClass"]("param");
Sign up to request clarification or add additional context in comments.

Comments

0

This will work for you

export class SomeComponent {

  constructor() {

    // suppose TheClass is the imported class name you want to instantiate
    let className: typeof TheClass = TheClass;

    /* should be the same as .. = new TheClass() */
    let superSpecial = new className(); // you "new" it as normal

  }

2 Comments

Please check my new answer, definitely gonna work for ya this time
His question centers around creating an instance based on a string. This doesn't answer that.
-2

You should use square bracket notation:

const classNameStr = 'example';
const myStore = {example: class {}};
const init = new myStore[classNameStr]();
// Or in case you class si global
const classNameStr = 'example';
(window as any).example = class {}; // if your class is already global this line should be deleted. I have put it here just to make the example work
const init = new window[classNameStr]();

Or Eval:

eval(`new ${className}()`);

3 Comments

your first example will not work, the second example will only work if TheClass is a global constructor
Stop referring to thiings in the global namespace using window. In fact, stop keeping things in the global namespace altogether.
@torazaburo I'm not suggesting to use window. I'm only showing how to access it in case it's already present in it. For example in case of native classes ( AudioContext, Audio, ecc.).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.