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. css - 如何控制鼠標事件?當處于down時會觸發(fā)其他效果,而up的時候則會取消所有效果?2. 求助一個Android控件名稱3. vim - docker中新的ubuntu12.04鏡像,運行vi提示,找不到命名.4. IOS app應(yīng)用軟件的id號怎么查詢?比如百度貼吧的app-id=4779278135. css - 關(guān)于offsetLeft和offsetTop6. javascript - video標簽無法識別的視頻格式怎么辦?7. python - flask的errorhandler(BaseError)重寫方法后怎么獲得更多信息8. html5 - mui dialog 如何配置type屬性9. javascript - 微信內(nèi)置瀏覽器的ua是多少?10. html5 - 小程序的swiper那個點可以給他居右?
