Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 974
Joba Avatar asked Oct 15 '25 04:10

Joba


1 Answers

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')
like image 67
Titian Cernicova-Dragomir Avatar answered Oct 17 '25 20:10

Titian Cernicova-Dragomir