Typescript создает объект типа, который происходит от переменной - PullRequest
0 голосов
/ 05 июня 2018

Метод возвращает мне тип класса: Widget.

Я хочу создать объект этого типа со следующим кодом:

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 TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

Есть ли "хорошая" версия (без eval) для создания объекта сданный тип класса?

1 Ответ

0 голосов
/ 05 июня 2018

Предполагая, что getWidgetType возвращает конструктор, вы можете вызвать new wType('foo') при условии, что подпись getWidgetType явно заявляет, что возвращает сигнатуру конструктора.

Например, этот код будет действительным:

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')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...