TS2341
TypeScriptERRORNotableClassesHIGH confidence

Property is private

What this means

An attempt was made to access a private member of a class from an external context.

Why it happens
  1. 1Accessing a private property from outside the class definition.
  2. 2Calling a private method from an instance of the class.
  3. 3A subclass attempting to access a private member of its parent class.
How to reproduce

Accessing a private property from an instance.

trigger — this will error
trigger — this will error
class MyClass {
  private secret: string;
  constructor() { this.secret = "abc"; }
}
const instance = new MyClass();
console.log(instance.secret);

expected output

error TS2341: Property 'secret' is private and only accessible within class 'MyClass'.

Fix 1

Create a public getter

WHEN The value needs to be exposed.

Create a public getter
class MyClass {
  private secret: string;
  constructor() { this.secret = "abc"; }
  getSecret() { return this.secret; }
}
const instance = new MyClass();
console.log(instance.getSecret());

Why this works

A public method can access private properties and return their values.

Fix 2

Change the property to 'public'

WHEN The property should be freely accessible.

Change the property to 'public'
class MyClass {
  public secret: string;
  constructor() { this.secret = "abc"; }
}
const instance = new MyClass();
console.log(instance.secret);

Why this works

Marking the property as public allows access from any context.

What not to do

Ignore the error with `// @ts-ignore`

This suppresses the error but does not fix the underlying design flaw of breaking encapsulation.

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