The this Parameter

Typing the context of traditional functions.

TypeScript3 min readConcept 22 of 54

The fake first parameter

In JavaScript, the this keyword inside a traditional function is completely dynamic. It depends entirely on *how* the function was called.

TypeScript allows you to declare exactly what type this should be by using a fake, reserved first parameter named this.

Preventing implicit any

If you use this.name inside a standalone function, TypeScript doesn't know what this is, so it implicitly types it as any. This disables type checking and can lead to runtime errors if the function is called without a proper context.

By typing the this parameter, you force the caller to provide the correct context.

Syntax

typescript type User = { name: string }; // The 'this' parameter must be the VERY FIRST parameter. function printName(this: User, prefix: string) { console.log(prefix + this.name); } // Error: The 'this' context of type 'void' is not assignable to type 'User'. // printName("Hello "); const obj = { name: "Alice", printName }; // OK: Called as a method, so 'this' is bound to 'obj'. obj.printName("Hello "); // OK: Explicitly binding 'this'. printName.call({ name: "Bob" }, "Hello ");

Try it

Toggle the compile step to watch the "fake" this parameter evaporate from the final JavaScript code.

function clickHandler(
this: HTMLButtonElement,
event: Event
) {
// Safe access!
this.disabled = true;
}

// Usage: Bound implicitly by the DOM
btn.addEventListener("click", clickHandler);

Type Checking Active

The this parameter is visible to the compiler. It ensures that inside the function body, this has all the properties of an HTMLButtonElement.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens to the 'this' parameter when the TypeScript code is compiled to JavaScript?

Remember this

  • To type this, define it as the very first parameter of the function.
  • It is completely erased at runtime and doesn't affect standard arguments.
  • It prevents this from implicitly being typed as any.
  • It cannot be used on arrow functions.

Done with this concept?

Mark it complete to track your progress. No login needed.