1
votes

My code is as follows:

$(function() {

    $("table").on("click", function() {
      const button = $(this);
    });

});

My error is:

this implicitly has type 'any' because it does not have a type annotation.

How do I fix this error?

Edit:

My tsconfig.json is as follows:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noImplicitAny": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "strict": true,
        "outDir": "dist",
        "baseUrl": ".",
        "paths": {
            "*": [
                "node_modules/*",
                "src/types/*"
            ]
        }
    },
    "include": [
        "src/**/*"
    ]
}

Edit 2:

I have the following in my package.json

"@types/jquery": "^2.0.41",
1
I am unable to reproduce that error. What version of TypeScript are you using? Do you have noImplicitAny: true in your tsconfig.json? - rossipedia
Yes, question edited. - Mary
Did you install jQuery types? e.g. npm install --save-dev @types/jquery - kingdaro
Yes, please see edit 2 above - Mary
Hm, the current version of the jquery types is 3.3.5, try upgrading? - kingdaro

1 Answers

3
votes

The problem is pretty much exactly what the compiler says:

error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.

4         const button = $(this);
                           ~~~~

That's because you have strict: true set in your tsconfig.json, which also turns on noImplicitThis. TypeScript's docs state that noImplicitThis means:

Raise error on this expressions with an implied any type.

And since you're not specifying the type of this before using it in your event handler, you get an error.

The fix is to specify the type of this:

$(function() {

    $("table").on("click", function(this: HTMLButtonElement) {
      const button = $(this);
    });

});

That will tell TypeScript what the intended type of this is in your event handler.

Alternatively, you could change strict to false in your tsconfig.json, but that may not be a viable option.