给出以下代码:
interface TaskInterface {
execute(): Promise<any>;
}
class Task implements TaskInterface {
private config: any = {};
public constructor(config: any) {
this.config = Object.assign({}, config);
}
public execute(): Promise<any> {
return Promise.resolve(`Hi, Mom ${this.config.info}`);
}
}
class Pop extends Task {
public constructor(config: any) {
super(config);
}
}
class Fetch extends Task {}
const taskData = { type: "pop" };
let TaskClass: Task;
if (taskData.type === "pop") TaskClass = Pop;
if (taskData.type === "fetch") TaskClass = Fetch;
const configuration = { settings: { power: "full" } };
if (TaskClass) {
const task = new TaskClass(configuration.settings);
task.execute();
}
我从TypeScript中收到以下错误:
src/test.ts:24:42 - error TS2739: Type 'typeof Pop' is missing the following properties from type 'Task': config, execute
24 if (taskData.type === "pop") TaskClass = Pop;
Did you mean to use 'new' with this expression?
src/test.ts:25:44 - error TS2739: Type 'typeof Fetch' is missing the following properties from type 'Task': config, execute
25 if (taskData.type === "fetch") TaskClass = Fetch;
Did you mean to use 'new' with this expression?
src/test.ts:28:16 - error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.
28 const task = new TaskClass(configuration.settings);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我想知道什么是能够实现此目标的正确方法?这是an online working example:
答案 0 :(得分:1)
类名是实例类型,要获取类本身的类型,您需要typeof className
:
const taskData = { type: "pop" };
let TaskClass: typeof Task;
if (taskData.type === "pop") TaskClass = Pop;
if (taskData.type === "fetch") TaskClass = Fetch;
const configuration = { settings: { power: "full" } };
if (TaskClass) {
const task = new TaskClass(configuration.settings);
task.execute();
}