Definitelytyped: Jquery can return HTMLCanvasElement too

Created on 7 Jan 2015  路  2Comments  路  Source: DefinitelyTyped/DefinitelyTyped

The following canvas angular directive code throw me an error on typescipt compilation :

error TS2339: Property 'getContext' does not exist on type 'HTMLElement'.

export function myCanvasDirective(): ng.IDirective {
    return {
      ...
      link: (scope: ng.IScope, elt: JQuery, attr : ng.IAttributes) => {
        var ctx = elt[0].getContext('2d');
        ...
    };
  };

This is because when JQuery is called with an index number, it returns an HTMLElement. Line 3559 jquery.d.ts

    [index: number]: HTMLElement;

Replace "HTMLElement" by "HTMLCanvasElement" or "any" works here. But I'm wondering if we can declare HTMLElement or HTMLCanvasElement as a return of JQuery ?

Most helpful comment

@paulsouche I think this is not a bug. you should use var ctx = (< HTMLCanvasElement >elt[0]).getContext('2d');

All 2 comments

@paulsouche I think this is not a bug. you should use var ctx = (< HTMLCanvasElement >elt[0]).getContext('2d');

Yes ! Thank you for the advice

Was this page helpful?
0 / 5 - 0 ratings