Sub topic 7
public: the default visibility
This chapter assumes you know basic TypeScript types, how JavaScript objects and this work, and the general idea of a class. You should also have seen a class with fields, a constructor, and methods. Here you will look at public, the visibility every class member gets when you write nothing.
What public means
A public member can be read, written, or called from anywhere: inside the class, inside subclasses, and in any code that holds an instance. If you leave out an access modifier, TypeScript treats the member as public. These two classes are identical to the compiler:
class ImplicitGreeter {
greeting = "Hello";
greet(name: string): string {
return `${this.greeting}, ${name}`;
}
}
class ExplicitGreeter {
public greeting = "Hello";
public greet(name: string): string {
return `${this.greeting}, ${name}`;
}
}
const a = new ImplicitGreeter();
const b = new ExplicitGreeter();
a.greeting = "Hi";
console.log(a.greet("Ada")); // Hi, Ada
console.log(b.greet("Ada")); // Hello, AdaOther languages differ here. Java and C# default to package-private or private visibility. TypeScript defaults to open access, which matches how JavaScript objects behave.
Where each modifier allows access
The table shows who can reach a member under each modifier. The public row is the one this chapter covers. The other rows come in later chapters.
| Modifier | Same class | Subclass | Outside code |
|---|---|---|---|
| `public` | Yes | Yes | Yes |
| `protected` | Yes | Yes | No |
| `private` | Yes | No | No |
Writing public explicitly
Because public is the default, the keyword changes nothing about the compiled program. It is erased during compilation, like all TypeScript-only syntax. There are still three reasons to write it.
- Parameter properties need a modifier. In a constructor, a parameter becomes a field only if it has
public,private,protected, orreadonlyin front of it. Without one, it is an ordinary parameter. - Team style rules. The
@typescript-eslint/explicit-member-accessibilitylint rule can require a modifier on every member. Some teams want the visibility of each member to be visible at a glance. - Intent. Writing
publicnext toprivatemembers marks the members you mean to be the API.
class User {
constructor(
public readonly id: string, // field created, public, read-only
public name: string, // field created, public
email: string // plain parameter, not a field
) {
console.log(`Created ${email}`);
}
}
const u = new User("u-1", "Ada", "[email protected]");
console.log(u.name); // Ada
// console.log(u.email); // Error: Property 'email' does not exist on type 'User'.If you forget the modifier on a constructor parameter, you get an error at the point of use, not at the declaration. This is the most common mistake with parameter properties.
Public members form your API
Everything public is part of the contract with callers. Once other code depends on a public field, renaming it or changing its type breaks that code. This is the main design reason to be careful with public.
Public fields are also writable unless you add readonly. Any code can put the object into a state you did not intend:
class Account {
public balance: number;
constructor(balance: number) {
this.balance = balance;
}
}
const acct = new Account(100);
acct.balance = -5000; // compiles; no validation runs
console.log(acct.balance); // -5000Public fields are fine for plain data with no rules. When a value must stay valid, make it private and expose a method or accessor that checks the input.
Leaking mutable internals
A public method that returns a private array hands out a reference to the real array. The caller can then change your internal state without going through your methods:
class Playlist {
public title: string;
private tracks: string[] = [];
constructor(title: string) {
this.title = title;
}
add(track: string): void {
this.tracks.push(track);
}
// Returns the internal array: callers can mutate it.
leakyList(): string[] {
return this.tracks;
}
// Read-only view at compile time.
list(): readonly string[] {
return this.tracks;
}
// Copy: safe at runtime too.
copyList(): string[] {
return [...this.tracks];
}
}
const pl = new Playlist("Focus");
pl.add("Track A");
pl.leakyList().push("Injected");
console.log(pl.list()); // ["Track A", "Injected"]readonly string[] stops callers from calling push in TypeScript code, but it is a compile-time check only. A copy protects the data at runtime as well.
Public and subclasses
A subclass can make an inherited member more visible. It cannot make one less visible. Widening protected to public is allowed:
class Base {
protected id = 1;
}
class Derived extends Base {
public override id = 2;
}
const d = new Derived();
console.log(d.id); // 2The reverse is an error. If Base declared public id and Derived declared protected id, TypeScript would reject Derived. Code that holds a Derived through a Base reference expects id to be accessible. A subclass must remain usable wherever its parent is expected.
Public does not mean enforced at runtime
Access modifiers are checked only by the compiler. The compiled JavaScript has no visibility at all, so every property is reachable, including those you marked private. That makes public the only modifier whose compile-time meaning matches the runtime behavior. If you need runtime enforcement, a later chapter covers #private fields.
Common errors
- Forgetting the modifier on a parameter property. The parameter is not a field, so
this.nameisundefinedor a compile error. - Making everything public by omission. If you never write modifiers, every field is part of your API and writable by any caller.
- Returning private collections directly. Return a copy or a
readonlytype. - Narrowing visibility in a subclass. TypeScript reports that the class incorrectly extends its base class.
Exercise
A class declares constructor(name: string, public age: number) {}. After const p = new Person("Ada", 36), which of p.name and p.age compiles, and why?
Show answer
Only p.age compiles. The public keyword on age turns it into a field. name has no modifier, so it is a plain constructor parameter and is not stored on the instance. Accessing p.name gives the error "Property 'name' does not exist on type 'Person'."
Exercise
A class has private items: string[] = [] and a public method getItems(): string[] { return this.items; }. Why can this break the class's rules, and what is one fix?
Show answer
The method returns the internal array itself, so a caller can call push or pop on it and change the class's state without going through its methods. One fix is to return a copy with return [...this.items];. Another is to change the return type to readonly string[], which blocks mutation at compile time only.