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. javascript - 如何在外部点击,跳转到网页后,显示指定的模块。2. mysql sql where id in(25,12,87) 结果集如何用按照 25 12 87排序?3. javascript - 在top.jsp点击退出按钮后,right.jsp进行页面跳转,跳转到login.jsp4. android自带时钟应用的这个效果是怎么做的5. 前端 - 提问关于background-image不显示的问题6. 使用未定义的常量user_id-假定为“user_id”7. java - 阿里的开发手册中为什么禁用map来作为查询的接受类?8. css - 关于background-position百分比的问题?9. 看不懂你这一步的操作10. java - Spring boot项目 可以通过ip+port+contentPath就直接显示所有的接口地址和数据信息,这是为什么???

网公网安备