【问题标题】:TypeScript interfaces and constructorsTypeScript 接口和构造函数
【发布时间】:2021-07-14 09:58:14
【问题描述】:

我的构造函数在接口中看不到方法,我遇到了这样的问题: “Board”类错误地实现了“IBoard”接口。 “Board”类型中缺少属性“makeBoard”,但在“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();
  }
}

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

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

    在 Board 类中添加 make board 方法。

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

    【讨论】:

      【解决方案2】:

      您需要添加接口描述的方法。您已经编写了 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;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-28
        • 1970-01-01
        • 1970-01-01
        • 2011-12-20
        相关资源
        最近更新 更多