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. android - NavigationView 的側滑菜單中如何保存新增項(通過程序添加)2. 老師 我是一個沒有學過php語言的準畢業生 我希望您能幫我一下3. php7.3.4中怎么開啟pdo驅動4. 關于thinkphp 5.1中,ajax提交數據url的格式寫法,加花括號就出錯,請老師指點5. http://run.php.cn/在線PHP程序運行結果不正確6. tp5 不同控制器中的變量調用問題7. Thinkphp5.1報錯不支持Redis8. ueditor上傳服務器提示后端配置項沒有正常加載,求助!!!!!9. 提示語法錯誤語法錯誤: unexpected ’abstract’ (T_ABSTRACT)10. 這段代碼既不提示錯誤也看不到結果,請老師明示錯在哪里,謝謝!
