How can I stop “property does not exist on type JQuery” syntax errors when using Typescript?

后端 未结 7 1234
天涯浪人
天涯浪人 2020-12-01 04:09

I am only using one line of jQuery in my application:

$(\"div.printArea\").printArea();

But this is giving me a Typescript error:

相关标签:
7条回答
  • 2020-12-01 04:36

    I think this is the most readable solution:

    ($("div.printArea") as any).printArea();
    
    0 讨论(0)
  • 2020-12-01 04:39

    You can also write it like this:

    let elem: any;
    elem = $("div.printArea");
    elem.printArea();
    
    0 讨论(0)
  • 2020-12-01 04:44

    You can also use the ignore syntax instead of using (or better the 'as any') notation:

    // @ts-ignore
    $("div.printArea").printArea();
    
    0 讨论(0)
  • 2020-12-01 04:46

    For your example, you'd add this:

    interface JQuery{
        printArea():void;
    }
    

    Edit: oops, basarat is correct below. I'm not sure why I thought it was compiling but I've updated this answer.

    0 讨论(0)
  • 2020-12-01 04:48

    You could cast it to <any> or extend the jquery typing to add your own method.

     (<any>$("div.printArea")).printArea();
    

    //Or add your own custom methods (Assuming this is added by yourself as a part of custom plugin)

    interface JQuery {
        printArea():void;
    }
    
    0 讨论(0)
  • 2020-12-01 04:49

    Since printArea is a jQuery plugin it is not included in jquery.d.ts.

    You need to create a jquery.printArea.ts definition file.

    If you create a complete definition file for the plugin you may want to submit it to DefinitelyTyped.

    0 讨论(0)
提交回复
热议问题