在ts爬蟲代碼練習時,用cheerio來獲取網頁中數據時
const viewCountTemp = $(e).find('.postDesc').eq(idx).find('.post-view-count').text() // "閱讀(5)"
infoItem.viewCount = parseInt(viewCountTemp.match(/.*\((.*)\)/)[1]) // 5 => "閱讀(5)".match(/.*\((.*)\)/) => ["閱讀(5)", "5", index: 0, input: "閱讀(5)", groups: undefined]
這段代碼是報錯的。
viewCountTemp.match(/.*\((.*)\)/)
error TS2531: Object is possibly 'null'.
解決方案: 在這個對象后面加一個感嘆號 ! ==> 是not null 的斷言操作符,不執行運行時檢查,告訴編譯器只需要知道這個東西
infoItem.viewCount =parseInt(viewCountTemp.match(/.*\((.*)\)/)![1])