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. 關于docker下的nginx壓力測試2. nignx - docker內nginx 80端口被占用3. docker-machine添加一個已有的docker主機問題4. docker鏡像push報錯5. python3.x - python連oanda的模擬交易api獲取json問題第五問6. angular.js - angular內容過長展開收起效果7. java - SSH框架中寫分頁時service層中不能注入分頁類8. node.js - 我是一個做前端的,求教如何學習vue,node等js引擎?9. 為什么我ping不通我的docker容器呢???10. html5 - 百度echart官網下載的地圖json數據亂碼
