search

Home  >  Q&A  >  body text

javascript - The problem of how to describe arrays using interfaces in 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)
  }

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)

某草草某草草2704 days ago967

reply all(1)I'll reply

  • 天蓬老师

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

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

    reply
    0
  • Cancelreply