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. mysql 查詢身份證號字段值有效的數據2. 視頻文件不能播放,怎么辦?3. node.js - nodejs開發中常用的連接mysql的庫4. python bottle跑起來以后,定時執行的任務為什么每次都重復(多)執行一次?5. mysql - 把一個表中的數據count更新到另一個表里?6. 請教使用PDO連接MSSQL數據庫插入是亂碼問題?7. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處8. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題9. visual-studio - Python OpenCV: 奇怪的自動補全問題10. Python爬蟲如何爬取span和span中間的內容并分別存入字典里?
