javascript - Typescript tạo đối tượng của một kiểu đến từ một biến
Một phương thức trả về cho tôi một kiểu lớp: Widget.
Tôi muốn tạo một đối tượng của loại này với mã sau:
const wType = def.getWidgetType(); // returns Widget as type
const obj = new wType('foo'); // use the const like a normal type with parameters
lấyLoạiWidget()
public getWidgetType(): any {
return TextWidget;
}
Lỗi
error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.Có phiên bản “tốt đẹp” (không dùng eval) để tạo một đối tượng với loại lớp đã cho không?
Câu trả lời #1
Giả sử những gì getWidgetType trả về là một hàm tạo, bạn có thể gọi new wType('foo') với điều kiện chữ ký của getWidgetType chỉ rõ nó trả về một chữ ký hàm tạo.
Ví dụ, đoạn mã này sẽ hợp lệ:
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')
