Explicit this parameters
Concept and syntax
A pseudo-parameter this: T specifies the receiver contract. It must appear first and is erased from JavaScript parameters. A regular function can receive a dynamic receiver via method invocation or call; an arrow function captures lexical this instead.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function add(this:{base:number},n:number){return this.base+n;}console.log(add.call({base:3},4),add.call({base:0},2));Expected output:
7 2Common mistake
Intentionally invalid; compile separately and do not execute.
function add(this:{base:number},n:number){return this.base+n;}add(4);Expected diagnostic: TS2684. A plain call does not supply the required receiver. Use an appropriate method call or call with a compatible object.
Practice and recap
Use bind to create a function with a fixed receiver.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Explicit this parameters — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function add(this:{base:number},n:number){return this.base+n;}console.log(add.call({base:3},4),add.call({base:0},2));Which diagnostic and explanation match the rejected example under the lesson settings?
function add(this:{base:number},n:number){return this.base+n;}add(4);