Course contentsShow
← TypeScript
Lesson 1186 of 1,79628. tsconfig in DepthFree lesson

noImplicitThis

Preventing implicit any on this in functions where the this context is unclear.

Preventing Implicit any on this in Functions Where the this Context is Unclear

You'll learn how TypeScript's noImplicitThis flag catches dangerous this usage before runtime surprises hit.

The Problem: When this Loses Its Type

You already know that this can be explicitly typed as the first parameter in functions. But what happens when you don't type it and TypeScript can't figure out what this should be? Without protection, this gets the type any, silently disabling all type safety.

function logUserName() {
  console.log(this.name); // 'this' is implicitly 'any' here
}

In this example, TypeScript doesn't know what object this function will be called on. If noImplicitThis is disabled, TypeScript assigns this the type any and lets you access any property—even if it doesn't exist at runtime.

What noImplicitThis Does

When you enable noImplicitThis in your tsconfig.json:

{
  "compilerOptions": {
    "noImplicitThis": true
  }
}

TypeScript requires you to explicitly type this in situations where it can't infer the context. The compiler will error on the function above, forcing you to either:

  1. Add an explicit this parameter:
function logUserName(this: { name: string }) {
  console.log(this.name); // Safe!
}
  1. Use an arrow function (which captures this from the surrounding scope):
const user = {
  name: "Alice",
  greet: () => {
    // Arrow functions don't have their own 'this'
    // They inherit from outer scope
  }
};
  1. Declare this: void if the function shouldn't use this at all.

When This Flag Matters

This protection is crucial in callback-heavy code, event handlers, or any function passed around where the calling context might change. It prevents the "works locally, crashes in production" scenarios caused by mysterious this bindings.

Key Takeaway: noImplicitThis forces you to be explicit about this types in functions where TypeScript can't infer the context, catching a common category of runtime errors at compile time. It's automatically enabled when you use strict: true.