簡體   English   中英

如何修復 Typescript 中的“元素”類型錯誤不存在屬性?

[英]How to fix property does not exist on type 'Element' error in Typescript?

運行構建時出現錯誤。 它說

TS2339:“元素”類型上不存在屬性“主體”。

代碼看起來像:

const testCode = document.createElementNS('http://example.com/x/x', 'testtestCode');
testCode.body = widgetBody; 

試圖在 const 之后添加 'as Element' 或 instanceof,但這不起作用。 有什么建議么?

在評論中提供更多信息后,很明顯您希望在自定義元素上使用自定義屬性。 你可以這樣做:

interface MyCustomElement {
    body: string;
    model: string;
}

const testCode = document.createElementNS('http://example.com/x/x', 'testtestCode')
                 as Element & MyCustomElement;
testCode.body = widgetBody; 

將變量轉換為 Element 和 MyCustomElement 將允許您訪問 Element 類型的正常屬性,同時還能夠訪問您的自定義屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM