Skip to content
webtype.orgwebtype.orgtsconfig

    ↑↓ move · ⏎ open · esc close

    tsconfig

    noImplicitThis

    this has to be knowable

    Inside a plain nested function, `this` is not the object you wrote it in — and without this flag it is silently `any`.

    Since
    TypeScript 2.0
    strict
    In strict
    In your tsconfig
    "noImplicitThis": true

    The same snippet both times. Only the option changed.

    With it off

    "noImplicitThis": false
    export const counter = {
      total: 0,
      bump: function () {
        return function () {
          return this.total
        }
      },
    }

    Compiles clean

    With it on

    "noImplicitThis": true
    export const counter = {
      total: 0,
      bump: function () {
        return function () {
          return this.total
        }
      },
    }

    Emits TS2683

    Why the compiler bothers

    JavaScript binds `this` at the call site, so a function nested inside a method gets whatever the caller supplies, which is usually nothing. This is the oldest bug in the language and it survives typing entirely, because an untyped `this` is `any` and `any.total` is fine. The flag makes the compiler admit it does not know, which is the point at which you either write an arrow function or declare a `this` parameter.

    Takeaway

    An arrow function has no `this` of its own, which is exactly why it is the fix.

    Where to go next

    22 options