javascript - TypeScript用接口如何描述數(shù)組的問題
問題描述
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開發(fā),上面的代碼在vscode中提示錯誤:Property ’slice’ does not exist on type ’History’.。
slice是數(shù)組方法,如果換成類似let a: string[] = [’Hello’]這種方式則slice方法可以正常使用不會報錯。
題主目前是還是TypeScript初學(xué)者,想問一下各位:
這種問題產(chǎn)生的原因是什么
類似this.state這種結(jié)構(gòu)的數(shù)據(jù)應(yīng)該怎么用interface描述(主要是history這個數(shù)組怎么描述)
問題解答
回答1:原因就是接口沒有正確繼承數(shù)組接口,導(dǎo)致數(shù)組的slice方法定義丟失
改成下面這樣
interface History extends Array<Squares>{}
相關(guān)文章:
1. bootstrp是col-md-12列的,只有col-md-10有內(nèi)容,可以讓沒有內(nèi)容的不占據(jù)位置嗎;2. python - Fiddler+Android模擬器抓取app,json數(shù)據(jù)被加密了,如何解析?3. thinkPHP5中獲取數(shù)據(jù)庫數(shù)據(jù)后默認選中下拉框的值,傳遞到后臺消失不見。有圖有代碼,希望有人幫忙4. java - 如何用圖畫的方式有效地表示多線程?5. wordpress里,這樣的目錄列表是屬于小工具還是啥?6. MySQL 使用 group by 之后然后 IFNULL(COUNT(*),0) 為什么還是會獲得 null7. 百度地圖 - Android app中準(zhǔn)備接入地圖sdk,百度VS高德哪個好一點?8. python 3.4 error: Microsoft Visual C++ 10.0 is required9. 我的怎么不顯示啊,話說有沒有QQ群什么的10. 常量在外面不加引號會報錯。
