javascript - The problem of how to describe arrays using interfaces in TypeScript
某草草
某草草 2017-07-05 10:36:13
0
1
916
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)
  }

The above code is part of the project code. The project is developed using React TypeScript. The above code prompts an error in vscode: Property 'slice' does not exist on type 'History'..

slice is an array method. If you change it to something like let a: string[] = ['Hello'], the slice method can be used normally without reporting an error.

The questioner is currently a beginner in TypeScript, and I would like to ask you:

  1. What is the cause of this problem

  2. How should data with a structure similar to this.state be described using an interface (mainly how to describe the history array)

某草草
某草草

reply all(1)
Peter_Zhu
  1. The reason is that the interface does not inherit the array interface correctly, resulting in the loss of the slice method definition of the array

  2. Change to the following

interface History extends Array<Squares>{}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!