Recently, the angular front-end framework was used to add graphic verification code authentication for application login. Since there was no ready-made plug-in, canvas + JS was used, which can also be used normally, but there was an error in the compilation stage:
ERROR in src/app/login/login.component.ts(84,19): error TS2339: Property 'getContext' does not exist on type 'HTMLElement'.
Although an error is reported, it can be executed normally. It’s strange. The error code is:
let c = document.getElementById("myCanvas") ; let ctx = c.getContext("2d");
Check the source code getContext() This method is. Later, I wonder if it is caused by the type. Therefore, use the type assertion (which does not affect the code operation, but only works in the compilation stage) to modify the code. Enter the following:
let c = document.getElementById("myCanvas") as HTMLCanvasElement; let ctx = c.getContext("2d");
The compilation passed normally. As we will see later, there is another assertion method:
let c = <HTMLCanvasElement> document.getElementById("myCanvas") ; let ctx = c.getContext("2d");
The above can be compiled because getContext() Yes HTMLCanvasElement Therefore, we need to specify the type
Above
Similar Posts:
- [Solved] typescript:error TS2531: Object is possibly ‘null’.
- Syntax error reported by JavaScript function: expected expression, got ‘;’
- Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported [Solved]
- How to Solve Error: Cannot set property ‘onclick’ of null
- React + typescript error collection [How to Solve]
- TS eslint angle bracket Error: Parsing error: Identifier expected
- Solve the problem of style in cannot read property ‘style’ of null
- Solve the problem of style in cannot read property ‘style’ of null
- Interaction between web browser and JavaScript in WPF
- Typeerror: error # 1009: the property or method referenced by an empty object cannot be accessed.