我有一些代碼獲取存盤在“markdownString”中的原始 Markdown 字串,并將其轉換為 HTML,并使用marked.js 庫在網路瀏覽器上顯示。我正在嘗試從頁面中獲取所有純文本值,并使用 TreeWalker 將其存盤在字串陣列中,然后遍歷節點。
我收到錯誤:
鍵入“節點 | null' 不可分配給型別 'Node'。型別“null”不可分配給型別“節點”。
嘗試使用時
currentNode = walker.nextNode();
const htmlString = marked(markdownString);
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
const walker = document.createTreeWalker(doc, NodeFilter.SHOW_TEXT);
const textList: string[] = [];
let currentNode = walker.currentNode;
while (currentNode != null) {
if (currentNode.textContent != null) {
textList.push(currentNode.textContent);
}
if (walker.nextNode() != null) {
currentNode = walker.nextNode();
} else {
break;
}
}
我不確定為什么 TypeScript 抱怨在進入塊分配'currentNode = walker.nextNode() 之前如果nextNode() 為null 已經檢查到位時無法將'null' 分配給'currentNode' '
uj5u.com熱心網友回復:
因為每次呼叫都nextNode()可能回傳不同的值。
要使用型別保護(又名“縮小”...您的if陳述句),您需要使用 TypeScript 可以做出合理假設的中間變數:
const nextNode = walker.nextNode();
if (nextNode != null) {
currentNode = nextNode;
} else {
break;
}
呼叫nextNode()兩次可能會導致一個未被發現的錯誤,因為它正在推進你的步行者,從而跳過所有其他節點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/522738.html
