Cholewka
Cholewka

Reputation: 963

TypeScript class definitions

I'm pretty sure that I can make "class templates" using TypeScript language, but I'm pretty sure I don't know how to declare methods that I don't know, what they have inside of them, but I'm sure that they're existing in the extended classes. And I have got this bunch of code:

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;

And everything seems to be fine, Visual Studio Code is recognizing that the methods onMouseMove, onMouseUp and onMouseDown exists and have provided properties, but in the Tool class I've got TypeScript errors:

Function implementation is missing or not immediately following the declaration.

Can someone please explain it to me?

Upvotes: 0

Views: 36

Answers (2)

Braiden Cutforth
Braiden Cutforth

Reputation: 198

I believe you are looking to make an abstract class.

See the documentation here:

https://www.typescriptlang.org/docs/handbook/classes.html#abstract-classes

Upvotes: 2

Tim Perry
Tim Perry

Reputation: 13216

It sounds like you're looking for abstract classes.

For your specific example, this should work:

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;

Upvotes: 3

Related Questions