在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'
。类型检查错误。
我不知道如何继续,我对typescript一无所知,而且程序是用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'));
发布于 2018-02-25 03:55:19
不是所有的HTML元素都有宽度,尽管画布有。您可以通过将类型从HTMLElement
缩小到HTMLCanvasElement
来解决这个问题(代码示例取自this TypeScript article)。
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');
而且,尽管我还没有尝试过,您可能会使用ts-ignore注释,即使它是一个JavaScript文件:
// @ts-ignore: I don't care that it might not be a HTML Canvas Element
const width = canvas.width;
https://stackoverflow.com/questions/48966233
复制相似问题