'this' implicitly has type 'any'
The 'this' keyword is being used in a context where its type cannot be inferred, and the 'noImplicitThis' compiler option is enabled.
- 1Using 'this' inside a function that is not a method of a class.
- 2In a callback function where the context of 'this' is lost.
- 3Defining a function using the 'function' keyword which has its own 'this' binding.
Using 'this' in a standalone function.
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.
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.
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.
✕ Disable 'noImplicitThis' in tsconfig.json
This removes a valuable safety check and can lead to unexpected behavior and runtime errors involving 'this'.
microsoft/TypeScript src/compiler/diagnosticMessages.json
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev