javascript - TypeScript用介面如何描述陣列的問題
某草草
某草草 2017-07-05 10:36:13
0
1
917
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這個陣列怎麼描述)

某草草
某草草

全部回覆(1)
Peter_Zhu
  1. 原因是接口沒有正確繼承數組接口,導致數組的slice方法定義丟失

  2. 改成下面這樣

interface History extends Array<Squares>{}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!