4

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?

2
  • 1
    What is the signature of getWidgetType ? Commented Jun 5, 2018 at 6:32
  • Show us your getWidgetType Commented Jun 5, 2018 at 6:33

1 Answer 1

5

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Your example helped me to fix my stuff. Thanks! In my code I just had to change the return type to getWidgetType(): new (id: string) => TextWidget

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.