JavaScript and TypeScript course Β· Module 7: Advanced TypeScript
Access Modifiers (public, private, protected)
In this lesson9
"Security in Jurassic Park is a matter of the highest importance," states John Hammond, president of InGen, firmly. "Some data and procedures must be accessible to all employees, others only to those with appropriate clearances, and still others are so critical that only top management has access to them."
Just like in Jurassic Park, in object-oriented programming, controlling access to class properties and methods is a fundamental aspect of good design. TypeScript offers three access modifiers that allow you to precisely define who can use specific class elements and to what extent: public, private, and protected.
Introduction to Access Modifiers
Access modifiers determine from which levels of code you can access a class's properties and methods:
- public - accessible from anywhere in the code (default)
- private - accessible only within the class itself
- protected - accessible within the class and inheriting classes
Let's see how these modifiers work in practice by implementing a dinosaur management system in Jurassic Park.
The public Modifier
Elements marked as public are accessible from anywhere in the code - both inside the class and on its instances. This is the default access modifier in TypeScript - if you don't specify any modifier, the element will automatically be marked as public.
class Dinosaur {
// Public properties
public name: string;
public species: string;
public age: number;
constructor(name: string, species: string, age: number) {
this.name = name;
this.species = species;
this.age = age;
}
// Public method
public displayInfo(): void {
console.log(`${this.name}: ${this.species}, ${this.age} years old`);
}
}
// Creating an instance
const rex = new Dinosaur("Rex", "Tyrannosaurus", 7);
// Accessing public properties and methods from outside the class
console.log(rex.name); // "Rex" - access to public property
rex.age = 8; // Modifying a public property
rex.displayInfo(); // Calling a public methodPublic properties and methods are like publicly available information in the park - for example, the park map, opening hours, or restroom locations. Everyone can use them without restrictions.
The private Modifier
Elements marked as private are accessible only within the class where they were defined. This encapsulation allows you to hide internal implementation details and prevents accidental state modifications from outside the class.
class HealthDiagnosis {
// Private properties
private id: string;
private testResults: Record<string, number>;
private notes: string;
public healthStatus: "healthy" | "sick" | "critical";
constructor(id: string) {
this.id = id;
this.testResults = {};
this.notes = "";
this.healthStatus = "healthy";
}
// Private method - used only inside the class
private analyzeResults(): "healthy" | "sick" | "critical" {
// Complex logic for analyzing test results
const bodyTemperature = this.testResults["bodyTemperature"] || 37;
const leukocyteLevel = this.testResults["leukocyteLevel"] || 7000;
if (bodyTemperature > 40 || leukocyteLevel > 15000) {
return "critical";
} else if (bodyTemperature > 38.5 || leukocyteLevel > 11000) {
return "sick";
} else {
return "healthy";
}
}
// Public methods using private properties
public addTestResult(name: string, value: number): void {
this.testResults[name] = value;
this.healthStatus = this.analyzeResults(); // Calling a private method
}
public addNote(note: string): void {
this.notes += note + "\n";
}
public getReport(): string {
return `
ID: ${this.id}
Health status: ${this.healthStatus}
Notes: ${this.notes || "None"}
`;
}
}
// Creating an instance
const raptorDiagnosis = new HealthDiagnosis("VL-001");
// Using the public API
raptorDiagnosis.addTestResult("bodyTemperature", 39.2);
raptorDiagnosis.addTestResult("leukocyteLevel", 12500);
raptorDiagnosis.addNote("Symptoms of viral infection");
console.log(raptorDiagnosis.healthStatus); // "sick" - access to public property
console.log(raptorDiagnosis.getReport()); // Calling a public method
// Attempting to access private elements
// console.log(raptorDiagnosis.id); // Error: Property 'id' is private
// console.log(raptorDiagnosis.testResults); // Error: Property 'testResults' is private
// raptorDiagnosis.analyzeResults(); // Error: Property 'analyzeResults' is privatePrivate properties and methods are like restricted procedures in the genetics laboratory - only authorized laboratory personnel (class methods) have access to them, while for the rest of the staff they are hidden for security reasons.
The protected Modifier
Elements marked as protected are accessible within the class where they were defined and in inheriting classes. This allows creating class hierarchies where derived classes have access to protected elements of the base class, but these elements remain inaccessible from outside the class hierarchy.
// Base class
class Animal {
// Protected properties
protected id: string;
protected species: string;
protected weight: number;
protected health: number; // 0-100
constructor(id: string, species: string, weight: number) {
this.id = id;
this.species = species;
this.weight = weight;
this.health = 100;
}
// Protected method
protected modifyHealth(change: number): void {
this.health = Math.max(0, Math.min(100, this.health + change));
}
// Public method
public displayStatus(): string {
return `${this.species} (${this.id}): Weight: ${this.weight}kg, Health: ${this.health}%`;
}
}
// Inheriting class
class Dinosaur extends Animal {
public name: string;
private aggressionLevel: number; // 0-10
constructor(id: string, species: string, name: string, weight: number) {
super(id, species, weight);
this.name = name;
this.aggressionLevel = 5;
}
// Method using protected elements from the base class
public feed(amount: number): void {
this.modifyHealth(amount * 5); // Access to protected method from base class
this.aggressionLevel = Math.max(0, this.aggressionLevel - 1);
console.log(`${this.name} has been fed. New health level: ${this.health}%`);
}
public takeDamage(amount: number): void {
this.modifyHealth(-amount); // Access to protected method from base class
this.aggressionLevel = Math.min(10, this.aggressionLevel + 2);
console.log(`${this.name} took damage. New health level: ${this.health}%`);
}
// Overriding base method using protected properties
public displayStatus(): string {
return `${this.name} (${this.species}): Weight: ${this.weight}kg, Health: ${this.health}%, Aggression: ${this.aggressionLevel}/10`;
}
}
// Inheriting class with modification of protected property
class MarineDinosaur extends Animal {
private divingDepth: number;
constructor(id: string, species: string, weight: number, divingDepth: number) {
super(id, species, weight);
this.divingDepth = divingDepth;
// Modifying a protected property in the constructor
this.health = 90; // Marine dinosaurs start with lower health
}
public swim(time: number): void {
// Using a protected method
this.modifyHealth(time > 10 ? -10 : 5);
console.log(`Marine dinosaur ${this.id} swam for ${time} minutes at a depth of ${this.divingDepth}m`);
console.log(`New health level: ${this.health}%`);
}
}
// Creating instances
const velociraptor = new Dinosaur("VL-002", "Velociraptor", "Blue", 150);
const mosasaur = new MarineDinosaur("MS-001", "Mosasaurus", 15000, 50);
// Using public methods
velociraptor.feed(2);
velociraptor.takeDamage(15);
console.log(velociraptor.displayStatus());
mosasaur.swim(15);
console.log(mosasaur.displayStatus());
// Attempting to access protected elements
// console.log(velociraptor.id); // Error: Property 'id' is protected
// console.log(mosasaur.health); // Error: Property 'health' is protected
// velociraptor.modifyHealth(50); // Error: Property 'modifyHealth' is protectedProtected properties and methods are like the park's security procedures - only authorized employees and their subordinates (base class and inheriting classes) have access to them, but not the park's guests (external code).
Constructor and Access Modifiers
TypeScript offers a special syntax for constructors that allows you to declare properties directly with access modifiers in constructor parameters. This is a shorthand notation that avoids code repetition.
// Traditional notation
class ParkEmployee {
private id: string;
public firstName: string;
public lastName: string;
protected accessLevel: number;
constructor(id: string, firstName: string, lastName: string, accessLevel: number) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.accessLevel = accessLevel;
}
}
// Shorthand notation with modifiers in constructor parameters
class ParkEmployeeShorthand {
constructor(
private id: string,
public firstName: string,
public lastName: string,
protected accessLevel: number
) {} // Empty constructor body - everything has already been initialized
}
// Both notations work identically
const employee1 = new ParkEmployee("EMP-001", "John", "Hammond", 10);
const employee2 = new ParkEmployeeShorthand("EMP-002", "Ellie", "Sattler", 8);
console.log(employee1.firstName, employee1.lastName); // "John Hammond"
console.log(employee2.firstName, employee2.lastName); // "Ellie Sattler"
// console.log(employee1.id); // Error: Property 'id' is private
// console.log(employee2.id); // Error: Property 'id' is privateThis shorthand syntax is especially useful in simple classes with many properties, as it reduces the amount of repetitive code.
Encapsulation and the Accessor Pattern (Getters and Setters)
One of the main reasons for using access modifiers is encapsulation - hiding implementation details and providing only a controlled interface for interacting with the class. Part of this approach is using getters and setters - special methods that control access to properties.
class EnclosureSecurity {
// Private properties
private _fenceStatus: "active" | "inactive" | "under_repair";
private _batteryChargeLevel: number; // 0-100
private _lastInspection: Date;
private _eventLog: string[];
constructor() {
this._fenceStatus = "active";
this._batteryChargeLevel = 100;
this._lastInspection = new Date();
this._eventLog = ["System started: " + new Date().toISOString()];
}
// Getters - controlled read access to private properties
get fenceStatus(): "active" | "inactive" | "under_repair" {
this.addLog("Fence status read");
return this._fenceStatus;
}
get batteryChargeLevel(): number {
this.addLog("Battery charge level read");
return this._batteryChargeLevel;
}
get lastInspection(): Date {
return new Date(this._lastInspection.getTime()); // Defensive copy
}
get securityReport(): string {
this.addLog("Security report generated");
return `
Fence status: ${this._fenceStatus}
Battery charge level: ${this._batteryChargeLevel}%
Last inspection: ${this._lastInspection.toLocaleDateString()}
Number of events in log: ${this._eventLog.length}
`;
}
// Setters - controlled write access to private properties
set fenceStatus(newStatus: "active" | "inactive" | "under_repair") {
this.addLog(`Changed fence status from ${this._fenceStatus} to ${newStatus}`);
this._fenceStatus = newStatus;
if (newStatus === "inactive") {
this.startSecurityProcedures();
}
}
// This setter contains validation logic
set batteryChargeLevel(newLevel: number) {
if (newLevel < 0 || newLevel > 100) {
throw new Error("Battery charge level must be between 0 and 100");
}
const oldValue = this._batteryChargeLevel;
this._batteryChargeLevel = newLevel;
this.addLog(`Changed battery charge level from ${oldValue}% to ${newLevel}%`);
if (newLevel < 20) {
this.addLog("WARNING: Low battery level!");
}
}
// Private helper method
private addLog(message: string): void {
this._eventLog.push(`${new Date().toISOString()}: ${message}`);
}
// Private business method
private startSecurityProcedures(): void {
this.addLog("ALERT: Emergency procedures activated!");
// Emergency handling logic
}
// Public method
public performInspection(): void {
this._lastInspection = new Date();
this.addLog("Fence inspection performed");
this._batteryChargeLevel = 100;
this._fenceStatus = "active";
}
// Public method
public getEventLog(): string[] {
// We return a copy to prevent modification of the original log
return [...this._eventLog];
}
}
// Using the class
const security = new EnclosureSecurity();
// Using getters
console.log("Fence status:", security.fenceStatus);
console.log("Battery level:", security.batteryChargeLevel);
// Using setters
security.fenceStatus = "under_repair";
security.batteryChargeLevel = 85;
// Using public methods
security.performInspection();
// Attempting to set an invalid value
try {
security.batteryChargeLevel = 110; // Will throw an error
} catch (e) {
console.error(e.message);
}
// Reading the report and logs
console.log(security.securityReport);
console.log("Event history:");
security.getEventLog().forEach((log, i) => {
console.log(`${i + 1}. ${log}`);
});Using getters and setters provides greater control over data access:
- We can add validation logic before changing a value
- We can perform additional operations when accessing data
- We can return defensive copies of objects to prevent accidental modifications
- We can log data access
Practical Example: Dinosaur Management System
Below is a comprehensive example of a dinosaur management system that uses all the discussed access modifiers to create a well-organized object-oriented architecture:
// Types and interfaces
type DinosaurHealthStatus = "healthy" | "sick" | "in treatment" | "sedated" | "deceased";
type DietType = "carnivore" | "herbivore" | "omnivore";
interface IMonitoring {
startMonitoring(): void;
stopMonitoring(): void;
getMonitoringStatus(): string;
}
// Abstract base class
abstract class ParkAnimal {
// Properties with different access modifiers
private _id: string;
protected _species: string;
protected _age: number;
protected _weight: number;
protected _status: DinosaurHealthStatus;
private _creationDate: Date;
private _lastUpdate: Date;
constructor(id: string, species: string, age: number, weight: number) {
this._id = id;
this._species = species;
this._age = age;
this._weight = weight;
this._status = "healthy";
this._creationDate = new Date();
this._lastUpdate = new Date();
}
// Getters
get id(): string {
return this._id;
}
get species(): string {
return this._species;
}
get age(): number {
return this._age;
}
get weight(): number {
return this._weight;
}
get status(): DinosaurHealthStatus {
return this._status;
}
// Setter with value checking and date update
set status(newStatus: DinosaurHealthStatus) {
if (this._status !== newStatus) {
this._status = newStatus;
this._lastUpdate = new Date();
this.logStatusChange(newStatus);
}
}
// Protected method accessible to inheriting classes
protected updateWeight(newWeight: number): void {
if (newWeight > 0) {
this._weight = newWeight;
this._lastUpdate = new Date();
} else {
throw new Error("Weight must be greater than zero.");
}
}
// Private method accessible only within this class
private logStatusChange(newStatus: DinosaurHealthStatus): void {
console.log(`[${new Date().toISOString()}] Status change ${this._id}: ${newStatus}`);
}
// Abstract method - every inheriting class must implement it
abstract getClinicalDescription(): string;
// Public method
public getBasicData(): string {
return `ID: ${this._id} | Species: ${this._species} | Age: ${this._age} years | Weight: ${this._weight} kg | Status: ${this._status}`;
}
}
// Inheriting class
class ParkDinosaur extends ParkAnimal implements IMonitoring {
// Private properties specific to dinosaurs
private _diet: DietType;
private _aggressionLevel: number; // 1-10
private _isMonitored: boolean;
private _lastMeal: Date | null;
private _assignedEnclosure: string | null;
constructor(
id: string,
species: string,
age: number,
weight: number,
diet: DietType,
aggressionLevel: number
) {
super(id, species, age, weight);
this._diet = diet;
this._aggressionLevel = this.validateAggressionLevel(aggressionLevel);
this._isMonitored = false;
this._lastMeal = null;
this._assignedEnclosure = null;
}
// Implementation of abstract method
getClinicalDescription(): string {
let description = `Dinosaur ${this.species} (ID: ${this.id})\n`;
description += `Health status: ${this.status}\n`;
description += `Age: ${this.age} years, Weight: ${this.weight} kg\n`;
description += `Diet: ${this._diet}\n`;
description += `Aggression level: ${this._aggressionLevel}/10\n`;
description += `Last meal: ${this._lastMeal ? this._lastMeal.toLocaleString() : "No data"}\n`;
return description;
}
// Implementation of IMonitoring interface
startMonitoring(): void {
this._isMonitored = true;
console.log(`Monitoring started for dinosaur ${this.id}`);
}
stopMonitoring(): void {
this._isMonitored = false;
console.log(`Monitoring stopped for dinosaur ${this.id}`);
}
getMonitoringStatus(): string {
return this._isMonitored ? "Active" : "Inactive";
}
// Public methods specific to dinosaurs
public feed(amount: number): void {
if (amount <= 0) {
throw new Error("Food amount must be greater than zero.");
}
const weightGain = this._diet === "carnivore" ? amount * 0.3 : amount * 0.2;
this.updateWeight(this.weight + weightGain);
this._lastMeal = new Date();
this._aggressionLevel = this.validateAggressionLevel(this._aggressionLevel - 1);
console.log(`Dinosaur ${this.id} was fed. New weight: ${this.weight} kg`);
}
public assignToEnclosure(enclosureCode: string): void {
this._assignedEnclosure = enclosureCode;
console.log(`Dinosaur ${this.id} was assigned to enclosure ${enclosureCode}`);
}
public sedate(): void {
this.status = "sedated";
this._aggressionLevel = 1;
console.log(`Dinosaur ${this.id} was sedated`);
}
public wake(): void {
if (this.status === "sedated") {
this.status = "healthy";
this._aggressionLevel = this.validateAggressionLevel(this._aggressionLevel + 2);
console.log(`Dinosaur ${this.id} was awakened`);
}
}
// Getters and setters
get diet(): DietType {
return this._diet;
}
get aggressionLevel(): number {
return this._aggressionLevel;
}
get lastMeal(): Date | null {
return this._lastMeal ? new Date(this._lastMeal.getTime()) : null;
}
get assignedEnclosure(): string | null {
return this._assignedEnclosure;
}
set aggressionLevel(level: number) {
this._aggressionLevel = this.validateAggressionLevel(level);
}
// Private helper method
private validateAggressionLevel(level: number): number {
return Math.max(1, Math.min(10, level));
}
}
// Using the system
function testDinosaurManagementSystem() {
// Creating dinosaurs
const trex = new ParkDinosaur("T-REX-01", "Tyrannosaurus Rex", 8, 7500, "carnivore", 9);
const stegosaurus = new ParkDinosaur("STEG-01", "Stegosaurus", 12, 5000, "herbivore", 4);
// Displaying basic information
console.log("=== BASIC DATA ===");
console.log(trex.getBasicData());
console.log(stegosaurus.getBasicData());
// Operations on dinosaurs
trex.feed(50);
trex.assignToEnclosure("CARNIVORE-A");
trex.startMonitoring();
stegosaurus.feed(80);
stegosaurus.assignToEnclosure("HERBIVORE-B");
// Status change
trex.status = "in treatment";
stegosaurus.sedate();
// Getting clinical reports
console.log("\n=== CLINICAL REPORTS ===");
console.log(trex.getClinicalDescription());
console.log(stegosaurus.getClinicalDescription());
// Monitoring status
console.log("\n=== MONITORING STATUS ===");
console.log(`T-Rex monitoring: ${trex.getMonitoringStatus()}`);
console.log(`Stegosaurus monitoring: ${stegosaurus.getMonitoringStatus()}`);
// Attempting to access private/protected elements
// The following lines would cause a compilation error:
// console.log(trex._id); // Error: Property '_id' is private
// console.log(trex._species); // Error: Property '_species' is protected
// trex.logStatusChange("healthy"); // Error: Property 'logStatusChange' is private
// trex.validateAggressionLevel(5); // Error: Property 'validateAggressionLevel' is private
}
// Running the test
testDinosaurManagementSystem();In the example above:
- Abstract base class (ParkAnimal) defines common properties and behaviors for all animals in the park
- Private properties (_id, _creationDate, _lastUpdate) are accessible only within the class
- Protected properties (_species, _age, _weight, _status) are accessible in the base class and inheriting classes
- Public getters and setters provide controlled access to properties
- Private methods (logStatusChange, validateAggressionLevel) are used as helper implementations accessible only within the class
- Protected methods (updateWeight) are accessible to inheriting classes
- Abstract method (getClinicalDescription) enforces implementation in inheriting classes
- Interface (IMonitoring) defines a contract that the Dinosaur class must implement
When and How to Use Access Modifiers
Choosing the appropriate access modifier depends on the specific use case, but there are a few general rules:
Use private for:
- Internal implementation details
- Data that should never be accessible outside the class
- Helper methods that are not part of the public API
- Properties that should only be modified through controlled setters
Use protected for:
- Properties and methods that need to be accessible in inheriting classes
- Implementations that can be extended or overridden in derived classes
- Data that is common to the entire class hierarchy but should not be accessible from outside
Use public for:
- Elements that form the public API interface of the class
- Methods that need to be accessible to all users of the class
- Properties that can be safely read or modified from outside
Summary
Access modifiers in TypeScript are a key tool for implementing good object-oriented design principles such as encapsulation, inheritance, and polymorphism. They allow precise control over access to class properties and methods, which promotes creating secure, modular, and maintainable code.
Just like in Jurassic Park, where the security system requires different access levels, a well-designed object-oriented system uses access modifiers to ensure that each element is accessible only to those who should actually have access to it.
John Hammond would summarize it briefly: "In Jurassic Park and in programming - security is paramount. Access modifiers are like security zones in the park - public for everyone, protected for specialists, and private only for top-level management. That's the key to maintaining order and preventing... surprises."
Code for this lesson: index.ts
// Access modifiers in TypeScript - Jurassic Park
console.log("Jurassic Park security system");
console.log("Demonstration of access modifiers: public, private, protected\n");
// ===========================================
// 1. Basic access modifiers
// ===========================================
console.log("=== 1. ACCESS MODIFIERS ===");
class BasicDinosaur {
// public - accessible from everywhere (default)
public name: string;
public species: string;
// private - accessible only in this class
private dnaSequence: string;
private securityCode: number;
// protected - accessible in this class and inheriting classes
protected age: number;
protected habitat: string;
constructor(name: string, species: string, dnaSequence: string) {
this.name = name;
this.species = species;
this.dnaSequence = dnaSequence;
this.securityCode = Math.floor(Math.random() * 10000);
this.age = 0;
this.habitat = "Enclosure";
}
// Public method
public getBasicInfo(): string {
return `${this.name} (${this.species})`;
}
// Private method
private validateDNA(): boolean {
return this.dnaSequence.length > 10;
}
// Protected method
protected calculateMaturity(): string {
if (this.age < 5) return "Young";
if (this.age < 15) return "Adult";
return "Old";
}
// Public access to private functionality
public isDNAValid(): boolean {
return this.validateDNA();
}
// Method with controlled access to private data
public getSecureInfo(accessCode: number): string | null {
if (accessCode === this.securityCode) {
return `DNA: ${this.dnaSequence.substring(0, 5)}...`;
}
return null;
}
}
const basicDino = new BasicDinosaur("Rex", "T-Rex", "ATCGATCGATCG");
console.log("Basic info:", basicDino.getBasicInfo());
console.log("Public fields:");
console.log(" Name:", basicDino.name);
console.log(" Species:", basicDino.species);
console.log("DNA valid:", basicDino.isDNAValid());
// These won't work - TypeScript compilation errors:
// console.log(basicDino.dnaSequence); // Error: private
// console.log(basicDino.age); // Error: protected
// basicDino.validateDNA(); // Error: private method
console.log("\n");
// ===========================================
// 2. Inheritance and modifiers
// ===========================================
console.log("=== 2. INHERITANCE AND MODIFIERS ===");
class CarnivorousDinosaur extends BasicDinosaur {
private huntingExperience: number;
protected packSize: number;
constructor(name: string, species: string, dnaSequence: string) {
super(name, species, dnaSequence);
this.huntingExperience = 0;
this.packSize = 1;
}
// Access to protected fields from base class
public setAge(newAge: number): void {
this.age = newAge; // OK - protected in the base class
console.log(`${this.name} is now ${this.age} years old`);
}
public getMaturityStatus(): string {
// Access to protected method from base class
return `${this.name} is ${this.calculateMaturity()}`;
}
// Overriding a protected method
protected calculateMaturity(): string {
const baseMaturity = super.calculateMaturity();
const huntingLevel = this.huntingExperience > 10 ? "Experienced hunter" : "Beginner";
return `${baseMaturity} - ${huntingLevel}`;
}
public hunt(): string {
this.huntingExperience++;
return `${this.name} is hunting! Experience: ${this.huntingExperience}`;
}
// Cannot access private fields from base class
// public getDNA(): string {
// return this.dnaSequence; // Error: private in base class
// }
}
const carnivoreDino = new CarnivorousDinosaur("Blue", "Velociraptor", "GCTAGCTAGCTA");
carnivoreDino.setAge(8);
console.log("Maturity status:", carnivoreDino.getMaturityStatus());
console.log("Hunting:", carnivoreDino.hunt());
console.log("\n");
// ===========================================
// 3. Encapsulation of sensitive data
// ===========================================
console.log("=== 3. ENCAPSULATION OF SENSITIVE DATA ===");
class SecureDinosaur {
public readonly id: string;
public name: string;
private dnaSequence: string;
private medicalHistory: string[];
private behaviorPatterns: Map<string, number>;
protected enclosureAccess: boolean;
protected emergencyProtocols: string[];
constructor(id: string, name: string, dna: string) {
this.id = id;
this.name = name;
this.dnaSequence = dna;
this.medicalHistory = [];
this.behaviorPatterns = new Map();
this.enclosureAccess = true;
this.emergencyProtocols = ["Tranquilizer", "Emergency Lock"];
}
// Controlled access to medical data
public addMedicalRecord(record: string, veterinarianCode: string): boolean {
if (this.validateVeterinarianAccess(veterinarianCode)) {
this.medicalHistory.push(`[${new Date().toISOString()}] ${record}`);
return true;
}
console.log("Unauthorized access to medical records");
return false;
}
public getMedicalHistory(veterinarianCode: string): string[] | null {
if (this.validateVeterinarianAccess(veterinarianCode)) {
return [...this.medicalHistory]; // A copy, not a reference
}
console.log("Unauthorized access to medical records");
return null;
}
// Controlled access to behavior patterns
public updateBehaviorPattern(pattern: string, intensity: number, researcherCode: string): boolean {
if (this.validateResearcherAccess(researcherCode)) {
this.behaviorPatterns.set(pattern, intensity);
console.log(`Behavior pattern '${pattern}' updated to ${intensity}`);
return true;
}
console.log("Unauthorized access to behavior data");
return false;
}
public getBehaviorAnalysis(researcherCode: string): string | null {
if (this.validateResearcherAccess(researcherCode)) {
const patterns = Array.from(this.behaviorPatterns.entries());
return patterns.map(([pattern, intensity]) => `${pattern}: ${intensity}`).join(", ");
}
console.log("Unauthorized access to behavior data");
return null;
}
// Private validation methods
private validateVeterinarianAccess(code: string): boolean {
return code === "VET-2023";
}
private validateResearcherAccess(code: string): boolean {
return code === "RESEARCH-2023";
}
// Public security methods
public getPublicInfo(): object {
return {
id: this.id,
name: this.name,
hasAccess: this.enclosureAccess,
lastUpdate: new Date().toISOString()
};
}
}
const secureDino = new SecureDinosaur("SEC-001", "Alpha", "CLASSIFIED-DNA");
console.log("Public info:", secureDino.getPublicInfo());
// Test access control
console.log("\nVeterinary access test:");
secureDino.addMedicalRecord("Routine checkup", "VET-2023"); // Authorized
secureDino.addMedicalRecord("Vaccination", "FAKE-CODE"); // Unauthorized
console.log("\nResearch access test:");
secureDino.updateBehaviorPattern("Aggression", 7, "RESEARCH-2023"); // Authorized
secureDino.updateBehaviorPattern("Calm", 3, "HACKER-CODE"); // Unauthorized
console.log("\n");
// ===========================================
// 4. Builder pattern with access modifiers
// ===========================================
console.log("=== 4. BUILDER PATTERN WITH MODIFIERS ===");
class DinosaurBuilder {
private dinosaur: {
name?: string;
species?: string;
diet?: string;
weight?: number;
dangerLevel?: number;
};
constructor() {
this.dinosaur = {};
}
public setName(name: string): DinosaurBuilder {
this.dinosaur.name = name;
return this;
}
public setSpecies(species: string): DinosaurBuilder {
this.dinosaur.species = species;
return this;
}
public setDiet(diet: string): DinosaurBuilder {
this.dinosaur.diet = diet;
return this;
}
public setWeight(weight: number): DinosaurBuilder {
this.dinosaur.weight = weight;
return this;
}
public setDangerLevel(level: number): DinosaurBuilder {
this.dinosaur.dangerLevel = level;
return this;
}
// Private validation
private validateDinosaur(): boolean {
const required = ['name', 'species', 'diet', 'weight', 'dangerLevel'];
return required.every(field => this.dinosaur[field as keyof typeof this.dinosaur] !== undefined);
}
public build(): CompleteDinosaur | null {
if (!this.validateDinosaur()) {
console.log("Validation failed - missing required fields");
return null;
}
return new CompleteDinosaur(
this.dinosaur.name!,
this.dinosaur.species!,
this.dinosaur.diet!,
this.dinosaur.weight!,
this.dinosaur.dangerLevel!
);
}
}
class CompleteDinosaur {
public readonly name: string;
public readonly species: string;
private readonly diet: string;
private readonly weight: number;
private readonly dangerLevel: number;
constructor(name: string, species: string, diet: string, weight: number, dangerLevel: number) {
this.name = name;
this.species = species;
this.diet = diet;
this.weight = weight;
this.dangerLevel = dangerLevel;
}
public getPublicProfile(): object {
return {
name: this.name,
species: this.species
};
}
public getDetailedInfo(securityClearance: number): object | null {
if (securityClearance >= this.dangerLevel) {
return {
name: this.name,
species: this.species,
diet: this.diet,
weight: this.weight,
dangerLevel: this.dangerLevel
};
}
console.log(`Insufficient security clearance. Required: ${this.dangerLevel}, Provided: ${securityClearance}`);
return null;
}
}
// Using Builder pattern
const builder = new DinosaurBuilder();
const completeDino = builder
.setName("Indominus Rex")
.setSpecies("Indominus Rex")
.setDiet("carnivore")
.setWeight(5500)
.setDangerLevel(10)
.build();
if (completeDino) {
console.log("Public profile:", completeDino.getPublicProfile());
console.log("\nAccess attempt with clearance 5:", completeDino.getDetailedInfo(5));
console.log("Access attempt with clearance 10:", completeDino.getDetailedInfo(10));
}
console.log("\n");
// ===========================================
// 5. Permissions and roles system
// ===========================================
console.log("=== 5. PERMISSIONS AND ROLES SYSTEM ===");
enum UserRole {
Visitor = 1,
Staff = 2,
Veterinarian = 3,
Researcher = 4,
Security = 5,
Administrator = 6
}
abstract class ParkUser {
protected name: string;
protected role: UserRole;
protected accessLevel: number;
constructor(name: string, role: UserRole) {
this.name = name;
this.role = role;
this.accessLevel = role;
}
public getName(): string {
return this.name;
}
public getRole(): string {
return UserRole[this.role];
}
// Abstract method - must be implemented in derived classes
public abstract canAccess(resource: string): boolean;
protected hasMinimumAccess(requiredLevel: number): boolean {
return this.accessLevel >= requiredLevel;
}
}
class ParkStaff extends ParkUser {
private department: string;
constructor(name: string, role: UserRole, department: string) {
super(name, role);
this.department = department;
}
public canAccess(resource: string): boolean {
const resourcePermissions: { [key: string]: number } = {
"public_areas": UserRole.Visitor,
"staff_rooms": UserRole.Staff,
"dinosaur_basic_info": UserRole.Staff,
"medical_records": UserRole.Veterinarian,
"research_data": UserRole.Researcher,
"security_systems": UserRole.Security,
"admin_panel": UserRole.Administrator
};
const requiredLevel = resourcePermissions[resource];
if (requiredLevel === undefined) {
console.log(`Unknown resource: ${resource}`);
return false;
}
const hasAccess = this.hasMinimumAccess(requiredLevel);
console.log(`${this.name} (${this.getRole()}) accessing ${resource}: ${hasAccess ? 'GRANTED' : 'DENIED'}`);
return hasAccess;
}
public getDepartment(): string {
return this.department;
}
}
// Test permissions system
const visitor = new ParkStaff("John Doe", UserRole.Visitor, "Tourist");
const veterinarian = new ParkStaff("Dr. Sarah Connor", UserRole.Veterinarian, "Medical");
const researcher = new ParkStaff("Dr. Alan Grant", UserRole.Researcher, "Paleontology");
const admin = new ParkStaff("Robert Muldoon", UserRole.Administrator, "Operations");
console.log("\nAccess control test:");
const resources = ["public_areas", "dinosaur_basic_info", "medical_records", "research_data", "admin_panel"];
const users = [visitor, veterinarian, researcher, admin];
users.forEach(user => {
console.log(`\n${user.getName()} (${user.getRole()}):`);
resources.forEach(resource => {
user.canAccess(resource);
});
});
console.log("\n");
// ===========================================
// 6. Getters and setters with access control
// ===========================================
console.log("=== 6. GETTERS AND SETTERS WITH ACCESS CONTROL ===");
class MonitoredDinosaur {
private _name: string;
private _health: number;
private _feedingSchedule: Date[];
private _isQuarantined: boolean;
private _lastHealthCheck: Date;
constructor(name: string) {
this._name = name;
this._health = 100;
this._feedingSchedule = [];
this._isQuarantined = false;
this._lastHealthCheck = new Date();
}
// Getter with access logging
get name(): string {
console.log(`Access logged: Reading name of ${this._name}`);
return this._name;
}
// Getter with permission validation
get health(): number {
console.log(`Health data accessed for ${this._name}`);
return this._health;
}
// Setter with validation
set health(value: number) {
if (value < 0 || value > 100) {
console.log(`Invalid health value: ${value}. Must be 0-100`);
return;
}
const oldHealth = this._health;
this._health = value;
this._lastHealthCheck = new Date();
console.log(`Health updated for ${this._name}: ${oldHealth} β ${value}`);
// Automatic quarantine at low health
if (value < 30 && !this._isQuarantined) {
this._isQuarantined = true;
console.log(`${this._name} automatically quarantined due to low health`);
}
}
// Computed property
get status(): string {
if (this._isQuarantined) return "Quarantined";
if (this._health < 30) return "Critical";
if (this._health < 60) return "Poor";
if (this._health < 80) return "Good";
return "Excellent";
}
// Setter with business logic
set isQuarantined(value: boolean) {
if (value !== this._isQuarantined) {
this._isQuarantined = value;
console.log(`${this._name} quarantine status: ${value ? 'ACTIVE' : 'INACTIVE'}`);
if (!value && this._health < 50) {
console.log(`Warning: Releasing ${this._name} from quarantine with health ${this._health}`);
}
}
}
get isQuarantined(): boolean {
return this._isQuarantined;
}
// Method with controlled access to history
public getFeedingHistory(accessLevel: number): Date[] | null {
if (accessLevel < UserRole.Staff) {
console.log(`Insufficient access to feeding history`);
return null;
}
return [...this._feedingSchedule];
}
public scheduleFeed(time: Date): void {
this._feedingSchedule.push(time);
console.log(`Feeding scheduled for ${this._name} at ${time.toLocaleTimeString()}`);
}
}
const monitoredDino = new MonitoredDinosaur("Alpha-7");
console.log("\nMonitored dinosaur test:");
console.log("Name:", monitoredDino.name);
console.log("Initial health:", monitoredDino.health);
console.log("Initial status:", monitoredDino.status);
// Test setters
monitoredDino.health = 25; // Automatic quarantine
console.log("Status after health drop:", monitoredDino.status);
monitoredDino.health = 85; // Health improvement
console.log("Status after recovery:", monitoredDino.status);
monitoredDino.isQuarantined = false; // Manual release from quarantine
// Test feeding schedule
monitoredDino.scheduleFeed(new Date(Date.now() + 3600000)); // In one hour
console.log("\n");
// ===========================================
// 7. Access modifiers summary
// ===========================================
console.log("=== 7. ACCESS MODIFIERS SUMMARY ===");
console.log("PUBLIC:");
console.log(" β’ Accessible from anywhere");
console.log(" β’ Default modifier in TypeScript");
console.log(" β’ Use for the class public API\n");
console.log("PRIVATE:");
console.log(" β’ Accessible only within the same class");
console.log(" β’ Implementation encapsulation");
console.log(" β’ Sensitive data protection\n");
console.log("PROTECTED:");
console.log(" β’ Accessible in the class and inheriting classes");
console.log(" β’ Sharing between class hierarchy");
console.log(" β’ Controlled access in inheritance\n");
console.log("READONLY:");
console.log(" β’ Can only be assigned in the constructor");
console.log(" β’ Protection against modification");
console.log(" β’ Immutable fields\n");
console.log("Access modifiers ensure security in Jurassic Park!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which access modifier in TypeScript allows access to a property only within the class and its derived classes?