[英]How do I resolve error "TS2339: Property 'gauge' does not exist on type 'JQuery<HTMLElement>'."
[英]How do I solve 'Property 'width' does not exist on type 'HTMLElement'.' when type checking Javascript (NOT Typescript) using // @ts-check in vscode?
在view.js文件中:
const canvas = document.getElementById('canvas');
...
export {
canvas,
};
在main.js文件中:
import * as view from '../src/view.js';
...
xPosition: view.canvas.width / 2,
給我'Property 'width' does not exist on type 'HTMLElement'
。 類型檢查錯誤。
我不知道如何繼續,我對打字稿沒有任何了解,而且程序是用javascript編寫的。 我讀過的所有解決方案都需要使用打字稿,這在本例中沒用。
我有什么辦法可以擺脫這個錯誤嗎?
編輯如果我添加以下內容:
/** @type {HTMLCanvasElement} */
const canvas = document.getElementById('canvas');
在我的view.js文件中它修復了我的main.js中的所有錯誤...但是,當我在包含上面一行的view.js文件中添加// @ts-check
時,我得到:
Type 'HTMLElement' is not assignable to type 'HTMLCanvasElement'.
Property 'height' is missing in type 'HTMLElement'.
編輯2
我似乎通過使用以下行添加一些括號來解決這個問題:
const canvas = /** @type {HTMLCanvasElement} */ (document.getElementById('canvas'));
並非所有HTML元素都有寬度,盡管畫布有。 您可以通過將類型從HTMLElement
縮小到HTMLCanvasElement
來解決問題(從此TypeScript文章中獲取的代碼示例)。
const canvas = document.getElementById('x');
if (isCanvas(canvas)) {
const width = canvas.width;
}
function isCanvas(obj: HTMLCanvasElement | HTMLElement): obj is HTMLCanvasElement {
return obj.tagName === 'CANVAS';
}
或者您可以使用類型注釋作弊:
const canvas = <HTMLCanvasElement>document.getElementById('x');
const width = canvas.width;
在JavaScript中,您可以使用JSDoc注釋來執行類型斷言:
/**
* @type {HTMLCanvasElement}
*/
const canvas = document.getElementById('x');
而且,雖然我沒有嘗試過,但即使它是一個JavaScript文件,你也可能會使用ts-ignore注釋:
// @ts-ignore: I don't care that it might not be a HTML Canvas Element
const width = canvas.width;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.