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. python2.7 - 在Eclipse开发Python,怎么去掉控制台输出的其他消息??2. css - div内部滚动,安卓没有滚动条(非body滚动),有什么办法可以显示吗?3. 数据库安全 - 在公网上部署mysql数据库,安全方面需要做到哪些注意事项4. 求大神帮我看看是哪里写错了 感谢细心解答5. python - django里GROUP BY 如何写这样的mysql语句?6. css - 定位为absolute的父元素中的子元素 如何设置在父元素的下面?7. html5 - ajax post请求后如何渲染到页面上8. python - 如何使用jsom.dumps获得完整的json数据?9. 如何判断数据库的库和表是否存在?10. javascript - 使用 vuex-router-sync寄存路由信息,this.$router params 不能赋值?
