Skip to content
Index

[TypeScript] Mark class properties as private

Tested with: TypeScript v5.6

TypeScript allows you to control the visibility of class properties (during type checking only) by using the private keyword.

class Foo {
private bar = "Hello";
}

Now, the bar property is only accessible within the Foo class, including within other instances of the Foo class.

class Foo {
private bar = "Hello";
compare(other: Foo) {
return this.bar === other.bar;
}
}
const foo = new Foo();
console.log(foo.bar); // Error: Property 'bar' is private and only accessible within class 'Foo'.
const otherFoo = new Foo();
foo.compare(otherFoo); // This works - returns `true`.

This is a compile-time check only. The private keyword does not affect the generated JavaScript code.

The bar property is still accessible from outside the class through other means, for example, using bracket notation.

foo["bar"]; // This works

Alternative: JavaScript private properties

TypeScript also supports the JavaScript private properties syntax — prefixing member names with the # symbol, which work at the JavaScript runtime level (where supported) and make these properties truly private.

class Foo {
#bar = "Hello";
}