The this Parameter
Typing the context of traditional functions.
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.
this.disabled = true;
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
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
thisfrom implicitly being typed asany. - It cannot be used on arrow functions.
Done with this concept?
Mark it complete to track your progress. No login needed.