Derby
Derby

Reputation: 23

TypeScript interfaces and constructors

My constructor can't see method in interface and i have such a problem: Class 'Board' incorrectly implements interface 'IBoard'. Property 'makeBoard' is missing in type 'Board' but required in type 'IBoard'.

How to handle it?

interface ICell {
    x: number,
    y: number,
    showBoard(): void,
    ctx: CanvasRenderingContext2D
}

export interface IBoard {
  ctx: CanvasRenderingContext2D,
  cell: Array<ICell>;
  canvas: HTMLCanvasElement,
  createCell(x:number, y:number, ctx:CanvasRenderingContext2D, color:string): void,
  createCells(): void,
  showBoard(): void,
  makeBoard(): void
}

export class Board implements IBoard {
  cell: Array<ICell> = [];
  canvas = document.getElementById('chessBoard-canvas') as HTMLCanvasElement;
  ctx = this.canvas.getContext('2d') as CanvasRenderingContext2D;
  
  constructor() {
    this.makeBoard();
  }
}

Upvotes: 1

Views: 138

Answers (2)

LaytonGB
LaytonGB

Reputation: 1404

You need to add the methods that the interface describes. You've written that an IBoard needs the createCell, createCells, showBoard, and makeBoard methods, yet you haven't written those methods on the Board class.

This should get rid of the error, but I'd recommend filling out the functions:

export class Board implements IBoard {
  cell: Array<ICell> = [];
  canvas = document.getElementById('chessBoard-canvas') as HTMLCanvasElement;
  ctx = this.canvas.getContext('2d') as CanvasRenderingContext2D;

  constructor() {
    this.makeBoard();
  }

  createCell(x,y,ctx,color) {
    return;
  }
  createCells() {
    return;
  }
  showBoard() {
    return;
  }
  makeBoard() {
    return;
  }
}

Upvotes: 0

michal.materowski
michal.materowski

Reputation: 447

You have to implement the function makeBoard in Board class. Interface is just a contract. It basically says: If you have class that implements this interface it must have methods, that you declared in the interface.

Add make board method to Board class.

 makeBoard(): void {
  throw new Error('Method not implemented.');
}

Upvotes: 2

Related Questions