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. python小白 關于類里面的方法獲取變量失敗的問題2. thinkPHP5中獲取數據庫數據后默認選中下拉框的值,傳遞到后臺消失不見。有圖有代碼,希望有人幫忙3. linux運維 - python遠程控制windows如何實現4. Python2中code.co_kwonlyargcount的等效寫法5. javascript - 如何用最快的速度C#或Python開發一個桌面應用程序來訪問我的網站?6. django - Python error: [Errno 99] Cannot assign requested address7. mysql數據庫做關聯一般用id還是用戶名8. [python2]local variable referenced before assignment問題9. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?10. python小白,關于函數問題
