Property is private
An attempt was made to access a 'private' property of a class from outside the class itself.
- 1Trying to read a private member from an instance of a class.
- 2Trying to write to a private member from an instance of a class.
- 3Accessing a private member from a derived class.
Accessing a private property on a class instance.
class User {
private name: string;
constructor(name: string) {
this.name = name;
}
}
const user = new User("Alice");
console.log(user.name);expected output
error TS2341: Property 'name' is private and only accessible within class 'User'.
Fix 1
Use a public method (getter)
WHEN The value needs to be exposed in a controlled way.
class User {
private name: string;
constructor(name: string) { this.name = name; }
public getName(): string { return this.name; }
}
const user = new User("Alice");
console.log(user.getName());Why this works
A public method can access private members and expose them.
Fix 2
Change the modifier to 'public'
WHEN The property is intended to be directly accessible.
class User {
public name: string;
constructor(name: string) { this.name = name; }
}
const user = new User("Alice");
console.log(user.name);Why this works
The 'public' modifier allows access from anywhere.
✕ Use bracket notation like user['name'] to bypass the check
This is a hack that circumvents the type system and violates the intended encapsulation of the class.
microsoft/TypeScript src/compiler/diagnosticMessages.json
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev