您的位置:首頁技術文章
文章詳情頁

javascript - TypeScript用接口如何描述數組的問題

瀏覽:90日期:2023-04-14 13:22:44

問題描述

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>{}

標簽: JavaScript
相關文章:
国产综合久久一区二区三区