Tìm kiếm trang web

typescript - Khi cố gắng sử dụng một lớp con, nhận được lỗi "Loại 'typeof ' thiếu các thuộc tính sau từ loại"


Cho đoạn mã sau:

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();
}

Tôi đang gặp các lỗi sau từ 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);
                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Tôi đang tự hỏi cách đúng đắn để có thể triển khai việc này là gì? Đây là một ví dụ trực tuyến đang hoạt động:

Câu trả lời #1

Tên lớp là kiểu của thể hiện, để lấy kiểu của lớp đó bạn cần 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();
}