首页 > 解决方案 > TypeScript 类定义

问题描述

我很确定我可以使用 TypeScript 语言制作“类模板”,但我很确定我不知道如何声明我不知道的方法,它们里面有什么,但我确保它们存在于扩展类中。我有这一堆代码:

class Tool {
  protected drawing: boolean;
  readonly assignedName: string;

  constructor(readonly name: string) {
    this.drawing = false;
    this.assignedName = name;
  }

  public getToolName(): string {
    return this.assignedName;
  }

  onMouseMove(
    xC: number,
    yC: number,
    canvasContext: CanvasRenderingContext2D
  ): void;
  onMouseUp(canvasContext: CanvasRenderingContext2D): void;
  onMouseDown(): void;
}

export default Tool;

一切似乎都很好,Visual Studio Code 正在识别 methods onMouseMoveonMouseUp并且onMouseDown存在并提供了属性,但是在Tool类中我遇到了 TypeScript 错误:

Function implementation is missing or not immediately following the declaration.

有人可以向我解释一下吗?

标签: typescript

解决方案


听起来您正在寻找抽象类

对于您的具体示例,这应该有效:

abstract class Tool {
  protected drawing: boolean;
  readonly assignedName: string;

  constructor(readonly name: string) {
    this.drawing = false;
    this.assignedName = name;
  }

  public getToolName(): string {
    return this.assignedName;
  }

  abstract onMouseMove(
    xC: number,
    yC: number,
    canvasContext: CanvasRenderingContext2D
  ): void;
  abstract onMouseUp(canvasContext: CanvasRenderingContext2D): void;
  abstract onMouseDown(): void;
}

export default Tool;

推荐阅读