Sub topic 7
`public`: The Default Visibility
This chapter assumes you know basic TypeScript types, JavaScript functions and objects, the this keyword, and the general idea of object-oriented programming.
A class member is public when code outside the class can access it. In TypeScript, public is the default visibility. These two declarations have the same meaning:
class User {
public name: string;
email: string;
}Both name and email can be read or changed by code that has a User instance.
Reading and changing public members
A public field represents part of the class's exposed API. An API is the set of names and operations that other code is allowed to use.
class User {
name: string;
email: string;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
describe(): string {
return `${this.name} <${this.email}>`;
}
}
const user = new User("Ada", "[email protected]");
console.log(user.name); // Ada
console.log(user.describe()); // Ada <[email protected]>
user.name = "Grace";
console.log(user.describe()); // Grace <[email protected]>The describe method is public because no visibility modifier is written. Code outside the class can call it.
You can write the modifier explicitly when you want the class's public API to be obvious:
class Product {
public constructor(
public name: string,
public price: number
) {}
public discountedPrice(rate: number): number {
return this.price * (1 - rate);
}
}Here, the constructor and all three members are public. The public fields can be accessed and changed directly:
const product = new Product("Keyboard", 100);
product.price = 90;
console.log(product.discountedPrice(0.1)); // 81Choosing what to expose
Public members are convenient, but every public field becomes a responsibility for the class. Other code may depend on its name, type, and behavior. Changing that member later can require changes throughout the program.
| Design choice | Effect |
|---|---|
| Public field | Callers can read and usually write the value directly |
| Public method | Callers can request an operation through a named method |
| No public member | Callers cannot use that part of the class directly |
Use public fields for simple data whose direct access is safe. Use a method when an operation needs validation, logging, calculated values, or other rules. Later, private members and accessors provide more control over this boundary.
The public surface
A useful way to review a class is to list the operations its callers need. Keep that public surface small enough that the class can change internally without breaking callers.
Exercise
In the Product class, what happens if price is declared without public?
Show answer
Nothing changes. Members without a modifier are public by default, so callers can still read and assign product.price.