Joba
Joba

Reputation: 898

Typescript create object of a type which comes from a variable

A method returns me a class type: Widget.

I want to create a object of this type with the following code:

const wType = def.getWidgetType(); // returns Widget as type
const obj = new wType('foo'); // use the const like a normal type with parameters

getWidgetType()

public getWidgetType(): any {
 return TextWidget;
}

Error

error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

Is there a "nice" version (without eval) to create a object with a given class type?

Upvotes: 4

Views: 1099

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

Assuming what getWidgetType returns is a constructor, you can invoke new wType('foo') provided the signature of getWidgetType explicitly states it returns a constructor signature.

For example this code would be valid:

class Definition<T> {
    // Takes in a constructor
    constructor(public ctor: new (p: string) => T) {

    }
    // returns a constructor (aka a function that can be used with the new operator)
    // return type annotation could be inferred here, was added for demonstrative purposes 
    getWidgetType() : new (p: string) => T{
        return this.ctor;
    }
}

const def = new Definition(class {
    constructor(p: string) {}
});

const wType = def.getWidgetType();
const obj = new wType('foo')

Upvotes: 5

Related Questions