javascript - TypeScript用接口如何描述数组的问题

查看:265
本文介绍了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这个数组怎么描述)

解决方案

  1. 原因就是接口没有正确继承数组接口,导致数组的slice方法定义丢失

  2. 改成下面这样

interface History extends Array<Squares>{}

这篇关于javascript - TypeScript用接口如何描述数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆