TS2324
TypeScriptERRORNotableClassesHIGH confidence

Property is private

What this means

An attempt was made to access a 'private' property of a class from outside the class itself.

Why it happens
  1. 1Trying to read a private member from an instance of a class.
  2. 2Trying to write to a private member from an instance of a class.
  3. 3Accessing a private member from a derived class.
How to reproduce

Accessing a private property on a class instance.

trigger — this will error
trigger — this will error
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.

Use a public method (getter)
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.

Change the modifier to 'public'
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.

What not to do

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.

Sources
Official documentation ↗

microsoft/TypeScript src/compiler/diagnosticMessages.json

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All TypeScript errors