在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编写的。我阅读的所有解决方案都需要使用TypeScript,这在此示例中毫无用处。
我有什么能摆脱此错误的事情?
编辑如果添加以下内容:
/** @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
来解决问题(从此打字稿文章中获取的代码示例(。
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;