TS2355
TypeScriptERRORCriticalConfigurationHIGH confidence

'this' implicitly has type 'any'

What this means

The 'this' keyword is being used in a context where its type cannot be inferred, and the 'noImplicitThis' compiler option is enabled.

Why it happens
  1. 1Using 'this' inside a function that is not a method of a class.
  2. 2In a callback function where the context of 'this' is lost.
  3. 3Defining a function using the 'function' keyword which has its own 'this' binding.
How to reproduce

Using 'this' in a standalone function.

trigger — this will error
trigger — this will error
function print() {
  console.log(this);
}

expected output

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

Fix 1

Use an arrow function

WHEN You want to preserve the 'this' context of the surrounding scope.

Use an arrow function
const print = () => {
  console.log(this);
};

Why this works

Arrow functions do not have their own 'this' binding; they inherit it from the enclosing execution context.

Fix 2

Provide an explicit type for 'this'

WHEN You need to specify the context for a function.

Provide an explicit type for 'this'
function print(this: Window) {
  console.log(this);
}

Why this works

TypeScript allows you to declare the type of 'this' as the first parameter of a function.

What not to do

Disable 'noImplicitThis' in tsconfig.json

This removes a valuable safety check and can lead to unexpected behavior and runtime errors involving 'this'.

Sources
Official documentation ↗

microsoft/TypeScript src/compiler/diagnosticMessages.json

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All TypeScript errors