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:
What is the cause of this problem
How should data with a structure similar to this.state be described using an interface (mainly how to describe the history array)
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
Change to the following