Explain the use of the 'this' keyword in TypeScript classes and functions.

Instruction: Provide examples to illustrate how 'this' behaves in different contexts within TypeScript.

Context: Tests the candidate's understanding of the 'this' keyword in TypeScript, including its use in classes and functions, and how to type 'this' for method chaining or callback functions.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

TypeScript follows JavaScript receiver rules. An ordinary function or method gets this from how it is called; a detached method is not automatically bound to its original object. An arrow function captures this from the surrounding scope.

```typescript class Calculator { private current = 0; add(this: Calculator, amount: number): Calculator { this.current += amount; return this; } getCurrent = () => this.current; } const calculator = new Calculator(); calculator.add(2).add(3); const addHere = calculator.add.bind(calculator); addHere(4);...

Related Questions