首頁  >  問答  >  主體

javascript - TypeScript用介面如何描述陣列的問題

interface Squares {
  squares: (null | string)[]
}

interface History {
  [index: number]: Squares
}

interface State {
  history: History
  stepNumber: number
  xIsNext: Boolean
}

class Game extends React.Component {
  state: State
  constructor() {
    super()
    this.state = {
      history: [{
        squares: Array(9).fill(null)
      }],
      stepNumber: 0,
      xIsNext: true
    }
  }
  
  handleClick(i: number) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1)
  }

以上程式碼為專案程式碼的一部分,專案使用React TypeScript開發,上面的程式碼在vscode中提示錯誤:Property 'slice' does not exist on type 'History'.

slice是陣列方法,如果換成類似let a: string[] = ['Hello']這種方式則slice方法可以正常使用不會報錯。

題主目前是還是TypeScript初學者,想問各位:

  1. 這種問題產生的原因是什麼

  2. 類似this.state這種結構的資料該怎麼用interface描述(主要是history這個陣列怎麼描述)

某草草某草草2637 天前919

全部回覆(1)我來回復

  • 天蓬老师

    天蓬老师2017-07-05 10:38:13

    1. 原因是接口沒有正確繼承數組接口,導致數組的slice方法定義丟失

    2. 改成下面這樣

    interface History extends Array<Squares>{}

    回覆
    0
  • 取消回覆