A private member restricts access to a property or method so that only the class defining it can use it. Class members are public by default; protected members are also available to subclasses. section 4.4.2
TypeScript's private keyword provides compile-time access control and disappears during JavaScript compilation. Use JavaScript's # syntax when privacy must affect generated JavaScript behavior, such as excluding a property from built-in serialization. section 6.5.1 section 4.4.2
Private members are useful when:
- An Angular component keeps implementation state private while exposing selected values through getters, as with a private TodoList field and public username and itemCount accessors. section 2.3.3
- A class needs to retain an internal dependency without exposing it as part of its public model; Order stores its Cart in #cart and uses it internally. section 6.5.1
- A subclass needs its own implementation detail: DiscountProduct declares a private discount constructor parameter while inheriting Product behavior. section 4.4.2
Internal cart state
In Order, declare #cart: Cart, assign it in the constructor, expose lines through c.lines(), and call #cart.clear() from clear(). The cart remains available to Order without becoming part of serialized order data. section 6.5.1
Listing 6.20. The contents of the order.model.ts file in the src/app/model folder
import { Injectable } from "@angular/core";
import { Cart, CartLine } from "./cart.model";
@Injectable()
export class Order {
id?: number;
name?: string;
address?: string;
city?: string;
state?: string;
zip?: string;
country?: string;
shipped: boolean = false;
#cart: Cart;
lines: CartLine[];
constructor(c: Cart) {
this.#cart = c;
this.lines = c.lines();
}
clear() {
this.id = undefined;
this.name = this.address = this.city = undefined;
this.state = this.zip = this.country = undefined;
this.shipped = false;
this.#cart.clear();
}
}
Inspect the complete Order model to see a private JavaScript field used alongside public order properties, a constructor, and a clearing method. section 6.5.1











