

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
JavaScript added support for private class members in ES2022 with the # syntax. TypeScript respects that syntax, and will give you compilation errors if you try to access private members outside of the class.
class SecretAgent {
// a private field
#id: string;
constructor(id: string) {
this.#id = id;
}
// a public method
getCodeName(): string {
const idToCodeNameMap: { [key: string]: string } = {
"007": "James Bond",
"006": "Alec Trevelyan",
// Add more mappings as needed
};
return idToCodeNameMap[this.#id] || "Unknown Agent";
}
}
const bond = new SecretAgent("007");
console.log(bond.getCodeName()); // "James Bond"
// Property '#id' is not accessible outside class 'SecretAgent' because it has a private identifier.
console.log(bond.#id);
In plain JavaScript, we'd only get the error at runtime, but with the same syntax in TypeScript, we get the error at compile time. Much better!