Access Modifiers and Parameter Properties
TypeScript supports public, protected, and private modifiers, plus readonly. public is the default. protected allows access in the class and subclasses; TypeScript's private restricts access through the type system, while JavaScript's #private fields provide runtime privacy. Parameter properties let a constructor parameter declare and initialize a field in concise syntax.
Use the least permissive access that fits the design. Do not confuse compile-time access modifiers with security boundaries: client-side code and emitted JavaScript can be inspected, and TypeScript's private keyword alone is not a runtime security feature.
Parameter properties
class Account {
constructor(
public readonly id: string,
private balance: number
) {}
getBalance(): number {
return this.balance;
}
}
const account = new Account("acct-1", 250);💡 The constructor parameters create and initialize fields.
id cannot be reassigned through this type; balance is only accessible inside the class according to TypeScript's access checking.Key Takeaways
publicis the default visibility.- TypeScript
privateis not the same as JavaScript#privateruntime privacy. - Use readonly for fields that should not be reassigned after initialization.
Knowledge Check
Which feature provides JavaScript runtime private-field semantics?