Syntax
function describe(this: { name: string }, prefix: string): string { /* ... */ }Examples
Typing a Function’s this Receiver: working example
Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints Hello Ada and Welcome Ada.
function describe(this: { name: string }, prefix: string): string {
return `${prefix}${this.name}`;
}
const user = { name: "Ada" };
console.log(describe.call(user, "Hello "));
const greeting = describe.bind(user, "Welcome ");
console.log(greeting());- Expected result: The program prints Hello Ada and Welcome Ada.
- The receiver must satisfy the named object shape under strict checking.
- The emitted function receives only prefix as an ordinary parameter.
Best practices
- Enable strictBindCallApply, included by strict, for useful receiver and argument checking.
- Use an arrow when lexical this is intended instead of declaring a dynamic receiver.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook