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初学者,想问一下各位:
这种问题产生的原因是什么
类似this.state这种结构的数据应该怎么用interface描述(主要是history这个数组怎么描述)
问题解答
回答1:原因就是接口没有正确继承数组接口,导致数组的slice方法定义丢失
改成下面这样
interface History extends Array<Squares>{}
相关文章:
1. linux - 编译安装mysql 5.6.232. angular.js - vue中类似于angular的ng-change的指令是?3. html5 - 在一个页面中 初始了两个swiper 不知道哪里错了 一直不对4. PHP能实现百度网盘的自动化么?5. android - 使用vue.js进行原生开发如何进行Class绑定6. node.js - 微信的自动回复问题7. node.js - vue服务端渲染如何部署到线上8. css3 - 请问一下在移动端CSS布局布局中通常需要用到哪些元素,属性?9. 网页爬虫 - python requests爬虫,如何post payload10. 如何把3个不同的MySQL数据库数据整合到一个MySQL数据库中?
