3

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?

Max Solid
  • 1,213
  • 3
  • 21
  • 32
  • 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. – Paarth Mar 26 '17 at 23:21
  • This is more of a javascript question see http://stackoverflow.com/questions/9803947/create-object-from-string – shusson Mar 26 '17 at 23:22
  • What you are looking for is a "factory"; google for that. –  Mar 27 '17 at 02:08

3 Answers3

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");
Saravana
  • 37,852
  • 18
  • 100
  • 108
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

  }
Trash Can
  • 6,608
  • 5
  • 24
  • 38
-3

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}()`);
Marco Turi
  • 65
  • 1
  • 8
  • your first example will not work, the second example will only work if `TheClass` is a global constructor – shusson Mar 26 '17 at 23:23
  • Stop referring to thiings in the global namespace using `window`. In fact, stop keeping things in the global namespace altogether. –  Mar 27 '17 at 02:07
  • @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.). – Marco Turi Mar 27 '17 at 07:41