

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Classes
incomplete
2: Private Class Members
incomplete
3: TypeScript Public and Private
incomplete
4: Protected Data Members
incomplete
5: Abstract Classes and Methods
incomplete
6: Classes Implement Interfaces
incomplete
7: Classes vs. Interfaces and Types
incomplete
8: The 'this' Type
incomplete
9: Parameter Properties
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Luckily TypeScript is smart enough to handle the funky this keyword for us, because as JavaScript developers, we know that the only question more difficult than "what is the meaning of life?" is "what is the value of this?".
class Counter {
private count: number = 0;
increment(): void {
// 'this' is implicitly typed as Counter
this.count++;
}
getCount(): number {
// 'this' is implicitly typed as Counter
return this.count;
}
}
this ParametersTypeScript is pretty smart (especially newer versions) and usually infers the type of this correctly. However, if you want to explicitly control the type of this, you can use the special this parameter:
class Counter {
private count: number = 0;
increment(this: Counter, n: number): void {
// 'this' is explicitly typed as Counter
// the `this` parameter is not available at runtime
// it is only used for type checking
this.count += n;
}
getCount(this: Counter): number {
// 'this' is explicitly typed as Counter
return this.count;
}
}
const counter = new Counter();
counter.increment(5);
console.log(counter.getCount());
// 5
We need to add some code to keep track of the number of times a RegularCustomer checks their balance.