我正在使用画布typescript
和扩展HTMLElement
自定义界面,但它Type 'HTMLElement' has no properties in common with type 'MyCanvas'
在终端中显示我,我该如何解决?
顺便说一下,版本typescript
是3.5.3
index.ts
import { MyCanvas } from './interface/canvas'
function init (): void {
const canvas: MyCanvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d');
canvas.width = 1000
canvas.height = 1000
}
canvas.ts
export interface MyCanvas extends HTMLElement {
width?:number;
height?: number;
getContext: Function;
}
问题是document.getElementById
返回HTMLElement
并且这个接口不能用作更广泛的接口。您可以使用MyCanvas
asHTMLElement
因为MyCanvas
包含所有属性,HTMLElement
但不能以其他方式使用。
通常修复很简单,您需要通过as
关键字断言类型以告诉编译器该函数返回应该断言为该类型。
const canvas = document.getElementById('canvas') as MyCanvas
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句