繁体   English   中英

TypeScript 接口和构造函数

[英]TypeScript interfaces and constructors

我的构造函数在接口中看不到方法,我有这样一个问题:“Board”类错误地实现了“IBoard”接口。 属性“makeBoard”在“Board”类型中缺失,但在“IBoard”类型中是必需的。

如何处理?

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

您必须在 Board 类中实现 makeBoard 函数。 接口只是一个契约。 它基本上说:如果你有实现这个接口的类,它必须有你在接口中声明的方法。

将 make board 方法添加到 Board 类。

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

您需要添加接口描述的方法。 您已经写过IBoard需要createCellcreateCellsshowBoardmakeBoard方法,但您还没有在Board类中编写这些方法。

这应该可以消除错误,但我建议填写以下功能:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM