You are tasked with creating a list of interview questions and answers for Object-Oriented Programming (OOP) using TypeScript. These questions should be genuine and designed to advance the interviewer's skills in OOP. Follow these guidelines:
Create questions that cover advanced OOP concepts in TypeScript.
Ensure each question is unique and non-repetitive.
Provide detailed, informative answers that explain the concepts thoroughly.
Include code examples in TypeScript where appropriate.
Focus on practical applications of OOP principles.
Format your output as follows:
<question_list>
<question_item>
Write the question here
Provide a detailed answer here. Include TypeScript code examples where relevant:
typescript
// Code example
Explain the code and its relevance to the OOP concept being discussed.
</question_item>
</question_list>
Generate a list of <num_questions>20</num_questions> questions and answers.
Remember to focus on TypeScript-specific implementations of OOP concepts and include advanced topics that will genuinely improve the interviewer's understanding of OOP in TypeScript.
Assistant
<question_list>
<question_item>
Explain the difference between an abstract class and an interface in TypeScript. When would you choose one over the other?
In TypeScript, both abstract classes and interfaces are used to define contracts within your application, but they have some key differences.
Abstract Class:
An abstract class is a class that cannot be instantiated directly. It may contain implementation details including fields and method implementations, as well as abstract methods that must be implemented by derived classes.
typescript
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('Moving along!');
}
}
class Dog extends Animal {
makeSound(): void {
console.log('Woof! Woof!');
}
}
const dog = new Dog();
dog.makeSound(); // Outputs: Woof! Woof!
dog.move(); // Outputs: Moving along!
In this example, Animal is an abstract class with an abstract method makeSound and a concrete method move. The Dog class extends Animal and implements the makeSound method.
Interface:
An interface declares a set of properties and methods that a class must implement, but it does not provide any implementation.
typescript
interface Animal {
makeSound(): void;
}
class Dog implements Animal {
makeSound(): void {
console.log('Woof! Woof!');
}
}
const dog = new Dog();
dog.makeSound(); // Outputs: Woof! Woof!
Here, Animal is an interface, and Dog implements it by providing a makeSound method.
When to Use Abstract Classes vs Interfaces:
Abstract Class:
Use when you want to share code among several closely related classes.
When you need to define non-static fields or provide default behavior.
When you want to enforce a particular base class.
Interface:
Use to define contracts that can be implemented by any class, regardless of its location in the class hierarchy.
When you want to implement multiple contracts (since TypeScript supports multiple interfaces but only single inheritance).
Interfaces are more flexible for defining shapes of objects.
Key Differences:
An abstract class can have implementation details and can contain state (fields), whereas an interface cannot.
A class can implement multiple interfaces but can only extend one class (abstract or not).
Interfaces can be used to define the shape of data (e.g., objects used as parameters), while abstract classes are strictly for class hierarchies.
Understanding the differences helps you choose the appropriate tool for designing your application's architecture.
</question_item>
<question_item>
How does TypeScript implement polymorphism, and can you provide an example of method overriding in a class hierarchy?
TypeScript supports polymorphism through inheritance and interfaces, allowing objects to be treated as instances of their parent class or interface rather than their actual class. This enables the use of a single interface to represent different underlying forms (data types).
Method Overriding:
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
Here's an example:
typescript
class Shape {
area(): number {
return 0;
}
}
class Rectangle extends Shape {
constructor(private width: number, private height: number) {
super();
}
area(): number {
return this.width * this.height;
}
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
function printArea(shape: Shape) {
console.log('The area is:', shape.area());
}
const rectangle = new Rectangle(10, 5);
const circle = new Circle(7);
printArea(rectangle); // Outputs: The area is: 50
printArea(circle); // Outputs: The area is: 153.93804002589985
In this example:
Shape is the base class with a method area.
Rectangle and Circle extend Shape and override the area method to provide specific implementations.
The printArea function accepts a parameter of type Shape but can handle any subclass due to polymorphism.
Explanation:
Polymorphism: Objects of different classes can be treated as objects of a common superclass.
Method Overriding: Subclasses provide their own implementation of methods defined in the superclass.
Practical Application:
Polymorphism allows for designing flexible and extensible code. You can write functions or classes that operate on general types, and they will work with any new subclasses without modification.
For instance, you can add a new Triangle class extending Shape with its own area method, and printArea will work without any changes.
typescript
class Triangle extends Shape {
constructor(private base: number, private height: number) {
super();
}
area(): number {
return (this.base * this.height) / 2;
}
}
const triangle = new Triangle(10, 5);
printArea(triangle); // Outputs: The area is: 25
This demonstrates polymorphism and method overriding in TypeScript, enabling flexible and reusable code.
</question_item>
<question_item>
What are generics in TypeScript, and how do they enhance the implementation of OOP concepts? Provide an example of a generic class.
Generics in TypeScript allow you to create components (functions, classes, interfaces) that work with a variety of data types rather than a single one. This provides a way to use type parameters as placeholders for the actual types that will be passed during implementation.
Enhancement of OOP Concepts:
Code Reusability: Generics allow you to write generalized code that can work with any data type.
Type Safety: Generics provide compile-time type checking, reducing runtime errors.
Flexibility: They enable you to create more flexible and maintainable code.
Example of a Generic Class:
Let's create a generic KeyValuePair class.
typescript
class KeyValuePair<K, V> {
constructor(public key: K, public value: V) {}
display(): void {
console.log(`Key: ${this.key}, Value: ${this.value}`);
}
}
const numberToString = new KeyValuePair<number, string>(1, "One");
numberToString.display(); // Outputs: Key: 1, Value: One
const stringToDate = new KeyValuePair<string, Date>("Today", new Date());
stringToDate.display(); // Outputs: Key: Today, Value: [Current Date]
Explanation:
The KeyValuePair class is defined with two generic type parameters K and V.
The constructor and display method use these generic types.
When creating instances of KeyValuePair, you specify the actual types for K and V.
Practical Application:
Generics are essential when implementing data structures like lists, trees, or maps, where the type of data stored is not known in advance or can vary.
Example with Constraints:
You can also add constraints to generics using extends.
typescript
interface HasId {
id: number;
}
class Repository<T extends HasId> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
findById(id: number): T | undefined {
return this.items.find(item => item.id === id);
}
}
class User implements HasId {
constructor(public id: number, public name: string) {}
}
const userRepo = new Repository<User>();
userRepo.add(new User(1, "Alice"));
userRepo.add(new User(2, "Bob"));
const user = userRepo.findById(1);
console.log(user?.name); // Outputs: Alice
Explanation:
The Repository class is generic over T, constrained to types that implement HasId.
This ensures that all items in the repository have an id property.
We create a User class that implements HasId and use Repository<User> to manage users.
Generics enhance OOP by providing flexibility, type safety, and reusability in your TypeScript applications.
</question_item>
<question_item>
Describe how access modifiers (public, private, protected, readonly) work in TypeScript classes. Provide examples demonstrating their use and explain scenarios where each would be appropriate.
Access Modifiers in TypeScript control the visibility and accessibility of class members (properties and methods).
public (default)
Members are accessible from anywhere.
private
Members are accessible only within the class where they are declared.
protected
Members are accessible within the class and its subclasses.
readonly
Members can be read but not modified after initialization.
Examples and Use Cases:
Public:
typescript
class Person {
public name: string;
constructor(name: string) {
this.name = name;
}
}
const person = new Person("Alice");
console.log(person.name); // Accessible: Alice
When to use: For members that are safe to expose and should be accessible from outside the class.
When to use: When you want subclasses to access certain members, but prevent access from outside the class hierarchy.
Readonly:
typescript
class Settings {
readonly version: string = "1.0.0";
constructor(public readonly appName: string) {}
}
const settings = new Settings("MyApp");
console.log(settings.appName); // Outputs: MyApp
// settings.appName = "NewApp"; // Error: Cannot assign to 'appName' because it is a read-only property
When to use: For constants or values that should not change after initialization.
Combining Modifiers:
You can combine readonly with other access modifiers.
typescript
class Point {
public readonly x: number;
public readonly y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
Practical Scenarios:
Use private to encapsulate data and prevent misuse.
Use protected to allow subclasses to interact with superclass properties/methods without exposing them publicly.
Use readonly to declare constants or immutable properties.
Use public for methods that define the class's interface to the outside world.
Proper use of access modifiers is crucial for implementing encapsulation, a core principle of OOP, leading to more maintainable and secure code.
</question_item>
<question_item>
What are decorators in TypeScript, and how can they be used to modify class behavior? Provide an example of a class decorator and explain how it alters the class.
Decorators in TypeScript are a feature that allows you to annotate and modify classes and class members. They are functions that can be attached to classes, methods, accessors, properties, or parameters to extend their functionality.
Types of Decorators:
Class Decorators
Method Decorators
Accessor Decorators
Property Decorators
Parameter Decorators
Class Decorator Example:
Let's create a class decorator that modifies the constructor of a class.
typescript
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
Explanation:
The sealed decorator takes the constructor function of the Person class.
It then calls Object.seal on both the constructor and its prototype, preventing new properties from being added.
How it Alters the Class:
With Object.seal, you cannot add new properties to the class or its instances, enforcing immutability of the class's structure.
Any attempt to add new properties will fail silently or throw an error in strict mode.
Using Class Decorators to Modify Behavior:
Another example is modifying the class to add new methods or replace existing ones.
typescript
function addGreeting<T extends { new (...args: any[]): {} }>(constructor: T) {
return class extends constructor {
greeting = "Hello";
greet() {
console.log(`${this.greeting}, ${this['name']}!`);
}
};
}
@addGreeting
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
const person = new Person("Alice");
person.greet(); // Outputs: Hello, Alice!
Explanation:
The addGreeting decorator returns a new class that extends the original constructor.
It adds a greeting property and a greet method.
When you create a new Person, it now has the greet method.
Practical Application:
Logging: Automatically log when instances are created or methods are called.
Dependency Injection: Inject services or dependencies into classes.
Runtime Checks: Add validation or constraints to class properties or methods.
Metadata Annotation: Add metadata to classes for frameworks like Angular.
Important Notes:
Experimental Feature: Decorators are an experimental feature and require enabling the experimentalDecorators compiler option.
Order Matters: When multiple decorators are applied, they are evaluated in reverse order (from bottom to top).
Target: The decorator function's arguments depend on the type of decorator (class, method, property, etc.).
Decorators provide a powerful way to employ metaprogramming in TypeScript, allowing developers to write cleaner and more expressive code by abstracting repetitive tasks and enhancing class behaviors.
</question_item>
<question_item>
Explain what mixins are in TypeScript and demonstrate how to implement multiple inheritance-like behavior using mixins. Provide a code example to illustrate this concept.
Mixins in TypeScript are a way to implement behavior from multiple classes into a single class, simulating multiple inheritance. Since TypeScript (and JavaScript) supports single inheritance, mixins provide a pattern for combining behaviors.
Implementing Mixins:
To create a mixin, you define a class or function that provides certain behaviors, and then you compose these behaviors into another class.
Example:
Let's create mixins for CanEat and CanWalk, and then compose them into a Person class.
typescript
// Define Mixin Behaviors
class CanEat {
eat(): void {
console.log('Eating');
}
}
class CanWalk {
walk(): void {
console.log('Walking');
}
}
// Mixin Function
function mixin<T extends new (...args: any[]) => {}>(Base: T, ...Mixins: any[]) {
Mixins.forEach(Mixin => {
Object.getOwnPropertyNames(Mixin.prototype).forEach(name => {
Base.prototype[name] = Mixin.prototype[name];
});
});
return Base;
}
// Compose Mixins into Person Class
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
mixin(Person, CanEat, CanWalk);
const person = new Person('John');
person.eat(); // Outputs: Eating
person.walk(); // Outputs: Walking
Explanation:
CanEat and CanWalk are classes providing specific behaviors.
The mixin function copies methods from Mixin classes to the Base class's prototype.
Person is the base class that we mix behaviors into.
After mixing, Person instances have eat and walk methods.
Using Interfaces for Type Safety:
We can improve type checking by using interfaces.
typescript
interface CanEat {
eat(): void;
}
interface CanWalk {
walk(): void;
}
class Person implements CanEat, CanWalk {
name: string;
constructor(name: string) {
this.name = name;
}
// Methods will be mixed in
}
mixin(Person, CanEat.prototype, CanWalk.prototype);
// No TypeScript errors when calling methods
const person = new Person('John');
person.eat();
person.walk();
Alternative Using Function Mixins:
Another approach is to use function-based mixins.
typescript
type Constructor<T = {}> = new (...args: any[]) => T;
function CanEat<TBase extends Constructor>(Base: TBase) {
return class extends Base {
eat() {
console.log('Eating');
}
};
}
function CanWalk<TBase extends Constructor>(Base: TBase) {
return class extends Base {
walk() {
console.log('Walking');
}
};
}
class Person {
constructor(public name: string) {}
}
const MixedPerson = CanWalk(CanEat(Person));
const person = new MixedPerson('John');
person.eat();
person.walk();
Explanation:
CanEat and CanWalk are mixin functions that return a class extending the base class.
MixedPerson is created by applying mixins to the Person class.
TypeScript understands the resulting class and its methods.
Practical Application:
Reusability: Share common behaviors across different classes without inheritance hierarchies.
Composition over Inheritance: Favoring composition allows for more flexible and maintainable code.
Avoiding Deep Hierarchies: Mixins help keep class hierarchies shallow.
Limitations:
Complexity: Can become complex and hard to maintain if overused.
Type Safety: Requires careful typing to ensure TypeScript understands the mixed-in methods.
Mixins in TypeScript provide a powerful technique to simulate multiple inheritance and compose classes from reusable behaviors, enhancing code reuse and flexibility.
</question_item>
<question_item>
How can you implement method overloading in TypeScript, and what are the key considerations? Provide an example of a class with overloaded methods.
Method Overloading in TypeScript allows a class to have multiple methods with the same name but different parameters. TypeScript supports method overloading via declarations, but the implementation must handle all overloads.
Key Considerations:
Overload signatures: Multiple method declarations with different parameter types and/or counts.
Implementation signature: A single method implementation that handles all overloads.
The implementation method must be compatible with all overload signatures.
Overload Signatures: Define the possible method signatures that the class supports.
Implementation Signature: The actual method that will be called, which must be compatible with all overloads.
Type Checking: TypeScript uses the overload signatures for type checking at compile-time and ensures that calls to add match one of the overloads.
Rules and Tips:
The implementation signature must be compatible with the overload signatures.
The implementation method should use type guards or assertions to handle different parameter types.
Only the overload signatures are visible to external callers, not the implementation signature.
Type Guards Example:
Adding type guards to ensure type safety within the method implementation.
typescript
add(a: any, b: any): any {
if (typeof a === 'number' && typeof b === 'number') {
return a + b; // Both numbers
} else if (typeof a === 'string' && typeof b === 'string') {
return a + b; // Both strings
} else if (typeof a === 'number' && typeof b === 'string') {
return a.toString() + b;
} else if (typeof a === 'string' && typeof b === 'number') {
return a + b.toString();
} else {
throw new Error('Invalid arguments');
}
}
Limitations:
Overloads cannot differ only by return type; parameter types must differ.
Overloading functions cannot be generic in the implementation signature.
Practical Application:
APIs with Flexible Parameters: Methods that accept different types of inputs.
Improved Intellisense: Overload signatures provide better code completion and type checking in IDEs.
Backward Compatibility: Supporting older method signatures while introducing new ones.
Method overloading in TypeScript enables developers to create more flexible and expressive APIs while maintaining strong type safety and clear documentation via overload signatures.
</question_item>
<question_item>
What are namespaces in TypeScript, and how do they differ from modules? Provide an example of using a namespace to organize code, and explain when you would use namespaces over modules.
Namespaces in TypeScript are a way to organize code into logical groups and prevent name collisions in the global scope. They are used to group related code together.
Modules, on the other hand, are files with import/export statements that allow code to be organized and shared across files using the module system.
Differences Between Namespaces and Modules:
Namespaces:
Internal modules.
Use the namespace keyword.
Do not generate module loaders (CommonJS, AMD, etc.).
Code is wrapped in an IIFE (Immediately Invoked Function Expression) when compiled.
Modules:
External modules.
Use import/export statements.
Rely on a module loader.
Encourage code splitting and lazy loading.
Example Using a Namespace:
typescript
namespace Geometry {
export namespace Areas {
export function circle(radius: number): number {
return Math.PI * radius ** 2;
}
export function rectangle(width: number, height: number): number {
return width * height;
}
}
export namespace Perimeters {
export function circle(radius: number): number {
return 2 * Math.PI * radius;
}
export function rectangle(width: number, height: number): number {
return 2 * (width + height);
}
}
}
// Using the namespace
const circleArea = Geometry.Areas.circle(5);
console.log(`Circle Area: ${circleArea}`);
const rectanglePerimeter = Geometry.Perimeters.rectangle(10, 5);
console.log(`Rectangle Perimeter: ${rectanglePerimeter}`);
Explanation:
Defined a Geometry namespace with nested namespaces Areas and Perimeters.
Functions are exported so they can be accessed outside the namespace.
Namespaces help in logically grouping related functions.
When to Use Namespaces Over Modules:
Legacy Codebases: When working in an environment where modules are not supported or not being used.
Script-Based Applications: When writing TypeScript that will be compiled into a single JavaScript file, perhaps for inclusion via a <script> tag.
Global Libraries: When creating libraries that will be used via global variables (e.g., in browser applications without bundlers).
Limitations of Namespaces:
Not recommended for new codebases using modern module systems (ES6 modules).
Can lead to larger global scope and potential name collisions if not managed carefully.
Less support for advanced module features like code splitting.
Modules Example:
Using modules instead of namespaces.
typescript
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// geometry.ts
import { add } from './math';
export function calculatePerimeter(width: number, height: number): number {
return add(add(width, width), add(height, height));
}
// main.ts
import { calculatePerimeter } from './geometry';
console.log(calculatePerimeter(10, 5)); // Outputs: 30
Advantages of Modules:
Better Support: Modern tooling and module systems (Webpack, Rollup).
Isolation: Each module has its own scope, reducing the chance of name collisions.
Tree-Shaking: Dead code elimination.
Asynchronous Loading: Dynamic imports for lazy loading.
Conclusion:
Use Namespaces: When you need to organize code in a global scope without a module system.
Use Modules: In modern applications that are structured with multiple files and rely on module loaders or bundlers.
While namespaces are still supported in TypeScript, leveraging ES6 modules is generally the preferred approach for organizing code in contemporary TypeScript projects.
</question_item>
<question_item>
How do you implement a singleton pattern in TypeScript? Provide a code example and explain how it ensures that only one instance of a class is created.
The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it.
Implementing Singleton in TypeScript:
typescript
class Singleton {
private static instance: Singleton;
private constructor() {
// Private constructor prevents direct instantiation
}
static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public someMethod(): void {
console.log('Executing some method');
}
}
// Usage
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();
console.log(singleton1 === singleton2); // Outputs: true
singleton1.someMethod(); // Outputs: Executing some method
Explanation:
Private Constructor:
The class constructor is marked as private, preventing external instantiation using new Singleton().
Static Instance Property:
A static property instance holds the singleton instance.
Static getInstance Method:
The getInstance method controls the access to the singleton instance.
It checks if an instance already exists; if not, it creates one.
Returns the singleton instance.
Ensuring a Single Instance:
Since the constructor is private, the only way to access the class is via the getInstance method.
The static instance variable ensures that the same instance is returned every time.
Resource Management: Managing access to resources like databases or file systems.
Alternative with Readonly Property:
typescript
class Singleton {
private static readonly _instance = new Singleton();
private constructor() {
// Private constructor
}
static get instance(): Singleton {
return this._instance;
}
public someMethod(): void {
console.log('Executing some method');
}
}
// Usage
const singleton1 = Singleton.instance;
const singleton2 = Singleton.instance;
console.log(singleton1 === singleton2); // Outputs: true
Thread Safety Considerations:
In single-threaded environments like JavaScript, thread safety is less of a concern.
If using TypeScript in a multi-threaded context (like Node.js with worker threads), additional synchronization mechanisms may be required.
Limitations:
Testing Challenges: Singleton can make unit testing more difficult due to shared state.
Global State Risks: Overuse can lead to tightly coupled code and difficulties in managing state.
Best Practices:
Ensure that the singleton class is stateless or manages state carefully.
Limit the use of singletons to scenarios where they provide clear benefits.
Implementing the singleton pattern in TypeScript ensures that a class has only one instance, providing controlled access and maintaining a single point of interaction with that instance throughout the application.
TypeScript supports encapsulation using access modifiers and also provides getters and setters (accessors) to control access to class properties.
Using Getters and Setters:
Getter (get): A method that gets the value of a specific property.
Setter (set): A method that sets the value of a specific property.
Example:
typescript
class Employee {
private _fullName: string;
constructor(private firstName: string, private lastName: string) {
this._fullName = `${firstName} ${lastName}`;
}
get fullName(): string {
return this._fullName;
}
set fullName(name: string) {
if (name && name.includes(' ')) {
[this.firstName, this.lastName] = name.split(' ');
this._fullName = name;
} else {
throw new Error('Invalid name format');
}
}
}
const employee = new Employee('John', 'Doe');
console.log(employee.fullName); // Outputs: John Doe
employee.fullName = 'Jane Smith';
console.log(employee.fullName); // Outputs: Jane Smith
// employee.fullName = 'Jane'; // Throws Error: Invalid name format
Explanation:
The _fullName property is private.
The fullName getter returns the _fullName.
The fullName setter validates the input and updates firstName, lastName, and _fullName.
Attempting to set fullName to an invalid format throws an error.
Benefits:
Controlled Access: Getters and setters allow for validation, transformation, or side effects when accessing or assigning properties.
Data Hiding: Prevent direct access to internal properties, maintaining control over how they're modified.
Compatibility: Allows changing the internal implementation without affecting external code.
Computation on Access: Can compute values on the fly rather than storing them.
Using Getters and Setters with Access Modifiers:
You can combine access modifiers with getters and setters for further encapsulation.
typescript
class Temperature {
private _celsius: number;
constructor(celsius: number) {
this._celsius = celsius;
}
get fahrenheit(): number {
return (this._celsius * 9) / 5 + 32;
}
set fahrenheit(value: number) {
this._celsius = ((value - 32) * 5) / 9;
}
}
const temp = new Temperature(0);
console.log(temp.fahrenheit); // Outputs: 32
temp.fahrenheit = 212;
console.log(temp.fahrenheit); // Outputs: 212
Explanation:
The Temperature class stores temperature in Celsius internally.
The fahrenheit getter computes the Fahrenheit value.
The fahrenheit setter converts Fahrenheit to Celsius and updates the internal state.
Practical Application:
Validation: Ensure that properties meet certain criteria before being set.
Lazy Initialization: Compute values when they're first accessed.
Event Triggering: Notify other parts of the application when a property changes.
Considerations:
Getters and setters can make debugging more complex if overly used.
Should not perform heavy computations or have significant side effects to keep property access predictable.
By using getters and setters, TypeScript allows developers to implement encapsulation effectively, providing control over how class properties are accessed and modified while maintaining a clean and intuitive interface.
</question_item>
<question_item>
What are advanced generics like conditional types and mapped types in TypeScript? Provide examples showing how conditional types can be used to create flexible and type-safe code.
Advanced Generics in TypeScript include concepts like conditional types and mapped types, which provide powerful tools for creating flexible and type-safe code.
Conditional Types:
Conditional types allow you to express types depending on a condition. The syntax is:
typescript
T extends U ? X : Y
This reads: If type T extends type U, then type is X; otherwise, it's Y.
Example: Conditional Type
typescript
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
Using Conditional Types in Generics:
typescript
function processValue<T>(value: T): T extends string ? string[] : T[] {
if (typeof value === 'string') {
return value.split('') as any;
} else {
return [value];
}
}
const resultString = processValue('Hello');
// resultString inferred as string[]
const resultNumber = processValue(42);
// resultNumber inferred as number[]
Explanation:
The return type depends on the type of T.
If T is string, the function returns string[].
Otherwise, it returns T[].
Mapped Types:
Mapped types allow you to create new types by transforming existing ones.
Example: Mapped Type
typescript
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
interface User {
name: string;
age: number;
}
type ReadonlyUser = Readonly<User>;
// Now all properties in ReadonlyUser are readonly
Conditional Logic in Types: Create types that adapt based on input types.
Advanced Conditional Types:
TypeScript supports more complex conditional types with inference.
Example: Extract Return Type
typescript
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
function getUser(id: number): User {
// Implementation
}
type UserReturnType = ReturnType<typeof getUser>;
// UserReturnType is User
Explanation:
The infer keyword allows us to capture the type R from the function's return type.
Template Literal Types with Conditional Types:
typescript
type EventName<T extends string> = T extends `on${infer U}` ? U : never;
type ClickEvent = EventName<'onClick'>; // 'Click'
type ChangeEvent = EventName<'onChange'>; // 'Change'
Considerations:
Complexity: Advanced types can make code harder to read if overused.
Compiler Limits: Excessive complexity may hit compiler limits or impact performance.
Conclusion:
Advanced generics like conditional and mapped types provide powerful mechanisms for creating flexible, type-safe abstractions in TypeScript, enabling developers to write highly generic and reusable code while maintaining strong type safety.
</question_item>
<question_item>
How do you use type guards to implement polymorphic behavior in TypeScript? Provide an example where type guards are used to differentiate between types in a union type.
Type Guards in TypeScript are expressions that perform runtime checks to ensure a variable is of a specific type. They allow you to safely access properties or methods on a variable by narrowing its type.
Implementing Polymorphic Behavior with Type Guards:
When working with union types, type guards help determine the actual type at runtime, enabling appropriate handling of each case.
Example:
typescript
type Shape = Circle | Rectangle;
interface Circle {
kind: 'circle';
radius: number;
}
interface Rectangle {
kind: 'rectangle';
width: number;
height: number;
}
function area(shape: Shape): number {
if (isCircle(shape)) {
// shape is Circle here
return Math.PI * shape.radius ** 2;
} else if (isRectangle(shape)) {
// shape is Rectangle here
return shape.width * shape.height;
}
throw new Error('Unknown shape');
}
// Type Guards
function isCircle(shape: Shape): shape is Circle {
return shape.kind === 'circle';
}
function isRectangle(shape: Shape): shape is Rectangle {
return shape.kind === 'rectangle';
}
// Usage
const myCircle: Circle = { kind: 'circle', radius: 5 };
const myRectangle: Rectangle = { kind: 'rectangle', width: 10, height: 5 };
console.log(area(myCircle)); // Outputs: 78.53981633974483
console.log(area(myRectangle)); // Outputs: 50
Explanation:
Union Type Shape: Combines Circle and Rectangle.
Type Guards isCircle and isRectangle:
Functions that check properties to determine the type.
Return a type predicate (shape is Circle) that informs TypeScript of the narrowed type.
Function area: Uses type guards to handle each shape appropriately.
In-line Type Guards with typeof:
For primitive types, you can use typeof.
typescript
function process(value: string | number) {
if (typeof value === 'string') {
// value is string
console.log(value.toUpperCase());
} else {
// value is number
console.log(value.toFixed(2));
}
}
Using instanceof with Classes:
typescript
class Dog {
bark() {
console.log('Woof!');
}
}
class Cat {
meow() {
console.log('Meow!');
}
}
type Pet = Dog | Cat;
function speak(pet: Pet) {
if (pet instanceof Dog) {
pet.bark();
} else if (pet instanceof Cat) {
pet.meow();
}
}
const myDog = new Dog();
const myCat = new Cat();
speak(myDog); // Outputs: Woof!
speak(myCat); // Outputs: Meow!
Discriminated Unions:
Using a common property to discriminate types.
typescript
interface Square {
kind: 'square';
size: number;
}
interface Triangle {
kind: 'triangle';
base: number;
height: number;
}
type Shape = Circle | Rectangle | Square | Triangle;
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'rectangle':
return shape.width * shape.height;
case 'square':
return shape.size ** 2;
case 'triangle':
return 0.5 * shape.base * shape.height;
default:
const _exhaustiveCheck: never = shape;
throw new Error(`Unhandled case: ${_exhaustiveCheck}`);
}
}
Explanation:
Switch Statement: Uses shape.kind to determine the type.
Exhaustiveness Checking: The never type ensures all cases are handled.
Benefits of Type Guards:
Type Safety: Prevent runtime errors by ensuring variables are of expected types.
Intellisense Support: Editors can provide appropriate autocomplete suggestions.
Clearer Code: Explicit type checks improve readability and maintainability.
Conclusion:
Type guards are essential for implementing polymorphic behavior in TypeScript, allowing you to work safely with union types and enabling the compiler to provide accurate type checking and error reporting.
</question_item>
<question_item>
Discuss how TypeScript's readonly modifier differs when used with arrays and tuples compared to classes. Provide examples illustrating the differences and explain the implications for immutability.
In TypeScript, the readonly modifier can be applied in different contexts:
Class Properties: It makes the property immutable, so it can't be reassigned after initialization.
Arrays and Tuples: It creates a new type of readonly array or tuple, disallowing modification methods.
readonly in Class Properties:
typescript
class Point {
readonly x: number;
readonly y: number = 0;
constructor(x: number) {
this.x = x;
// this.y = 1; // Error: Cannot assign to 'y' because it is a read-only property
}
}
const point = new Point(5);
// point.x = 10; // Error: Cannot assign to 'x' because it is a read-only property
Explanation:
Once Assigned:readonly properties can be assigned once, typically during initialization.
Immutability of Property Reference: The property reference cannot change, but if it's an object, the object's contents can still be mutable.
readonly with Arrays:
typescript
let arr: number[] = [1, 2, 3];
let readonlyArr: readonly number[] = [1, 2, 3];
// arr[0] = 10; // Allowed
// arr.push(4); // Allowed
// readonlyArr[0] = 10; // Error: Index signature in type 'readonly number[]' only permits reading
// readonlyArr.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'
// Type Casting
arr = readonlyArr as number[]; // Allowed but unsafe
Explanation:
Immutable Methods: Methods that modify the array (e.g., push, pop, splice) are not available on readonly arrays.
Read-Only Index Access: You can read elements but cannot assign to indexes.
readonly with Tuples:
typescript
type Point = [number, number];
const point: Point = [5, 10];
point[0] = 15; // Allowed
const readonlyPoint: readonly [number, number] = [5, 10];
// readonlyPoint[0] = 15; // Error: Cannot assign to '0' because it is a read-only property
Implications for Immutability:
Shallow Immutability for Arrays and Tuples: Using readonly creates a shallow immutable array or tuple. Elements cannot be replaced, but if the elements are objects, their properties can still be modified.
Deep Immutability Requires Additional Types: For deep immutability, you need to define recursive types or use utility types.
Readonly vs. const:
const Declarations:
Used with variable declarations.
Prevents reassignment of the variable reference.
Does not make the contents immutable.
readonly Modifier:
Used in type declarations (classes, interfaces, type aliases).
Prevents modification of properties or array elements.
Example with Objects in Arrays:
typescript
interface User {
name: string;
age: number;
}
const users: readonly User[] = [{ name: 'Alice', age: 30 }];
// users.push({ name: 'Bob', age: 25 }); // Error: Property 'push' does not exist
users[0].age = 31; // Allowed; the object is still mutable
Making Deeply Immutable Types:
typescript
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
const users: DeepReadonly<User[]> = [{ name: 'Alice', age: 30 }];
// users[0].age = 31; // Error: Cannot assign to 'age' because it is a read-only property
Conclusion:
Classes:readonly properties cannot be reassigned after the initial assignment.
Arrays/Tuples:readonly arrays prevent methods that modify the array and disallow index assignments.
Immutability: While readonly enhances immutability, it is shallow; full immutability requires deeper solutions.
Understanding the differences in readonly usage helps write safer and more predictable code, especially when managing state in applications where immutability is important.
</question_item>
<question_item>
How can you create a conditional type that extracts the keys of an interface whose values are of a specific type? Provide an example and explain how it works.
You can create a conditional type in TypeScript that extracts the keys of an interface with values of a specific type by using mapped types, keyof, and conditional types.
type NonNullableKeys<T> = {
[K in keyof T]: null extends T[K] ? never : K;
}[keyof T];
interface Example {
a: string;
b: string | null;
c: number;
d?: number;
}
type NonNullableKeysExample = NonNullableKeys<Example>;
// Result: "a" | "c"
Explanation:
Checks if null extends T[K] (i.e., if the property can be null).
Includes keys where the value is not nullable.
Practical Use Cases:
Filtering Properties: Create functions or utilities that operate only on properties of a certain type.
Form Handling: Extract fields of a certain type for validation or processing.
Data Transformation: Map over objects and selectively process properties.
Limitations:
Complexity: Advanced types can become difficult to read and maintain.
Type Inference: Sometimes requires explicit type annotations.
Conclusion:
By leveraging conditional types, you can create powerful type transformations in TypeScript, enabling more expressive and safer code by operating precisely on types and their properties.
</question_item>
<question_item>
Explain what a discriminated union is in TypeScript and how it benefits type safety. Provide an example with code demonstrating how to use discriminated unions effectively.
A Discriminated Union (also known as a tagged union or algebraic data type) in TypeScript is a type composed of several interfaces with a common property (the discriminant) that distinguishes among them.
Benefits:
Enhanced type safety.
Exhaustiveness checking.
Clear and concise code for union types.
Key Components:
Union of Interface Types: Each interface represents a variant.
Common Literal Property: A property (discriminant) with a unique literal value in each variant.
Type Guards (often using switch or if): Narrow the type based on the discriminant.
Example:
Let's define shapes with a discriminant kind.
typescript
interface Circle {
kind: 'circle';
radius: number;
}
interface Rectangle {
kind: 'rectangle';
width: number;
height: number;
}
interface Triangle {
kind: 'triangle';
base: number;
height: number;
}
type Shape = Circle | Rectangle | Triangle;
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'rectangle':
return shape.width * shape.height;
case 'triangle':
return 0.5 * shape.base * shape.height;
default:
// Exhaustive check
const _exhaustiveCheck: never = shape;
throw new Error(`Unhandled case: ${_exhaustiveCheck}`);
}
}
Explanation:
Discriminant kind: Each interface has a kind property with a unique string literal value.
Union Type Shape: Combines all shape interfaces.
Function area: Uses a switch statement to narrow the type based on shape.kind.
Exhaustiveness Checking:
The default case ensures all possible variants are handled.
Assigning shape to a variable of type never causes a compile-time error if any variant is unhandled.
Benefits of Discriminated Unions:
Type Narrowing:
TypeScript can infer the type within each case.
You get autocompletion and type checking specific to that variant.
Exhaustiveness Checking:
Ensures all possible variants are considered.
Reduces runtime errors due to unhandled cases.
Using in Function Overloads:
You can also use discriminated unions with function overloads:
typescript
function getPerimeter(shape: Circle): number;
function getPerimeter(shape: Rectangle): number;
function getPerimeter(shape: Triangle): number;
function getPerimeter(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return 2 * Math.PI * shape.radius;
case 'rectangle':
return 2 * (shape.width + shape.height);
case 'triangle':
// Assume equilateral triangle for simplicity
return 3 * shape.base;
default:
const _exhaustiveCheck: never = shape;
throw new Error(`Unhandled case: ${_exhaustiveCheck}`);
}
}
TypeScript will prompt you to handle the new kind wherever Shape is used.
Type Guards with if Statements:
typescript
function describeShape(shape: Shape): string {
if (shape.kind === 'circle') {
return `Circle with radius ${shape.radius}`;
} else if (shape.kind === 'rectangle') {
return `Rectangle ${shape.width}x${shape.height}`;
} else if (shape.kind === 'triangle') {
return `Triangle with base ${shape.base} and height ${shape.height}`;
} else {
const _exhaustiveCheck: never = shape;
return `Unknown shape: ${_exhaustiveCheck}`;
}
}
Conclusion:
Discriminated unions are a powerful feature in TypeScript that enhance type safety by allowing the compiler to accurately narrow types and ensure all possible cases are handled, leading to more robust and maintainable code.
</question_item>
<question_item>
Describe how the abstract keyword works with classes and methods in TypeScript. Provide an example of an abstract class with abstract and concrete methods, and explain how subclasses should implement them.
The abstract keyword in TypeScript is used to define abstract classes and methods.
Abstract Classes:
Cannot be instantiated directly.
Serve as base classes from which other classes derive.
Can include abstract methods and concrete methods.
new Animal('Generic') // Error: Cannot create an instance of an abstract class.
Implementing Abstract Methods:
Subclasses must provide concrete implementations of abstract methods.
If a subclass does not implement all abstract methods, it must be declared as abstract.
Partial Implementation:
typescript
abstract class Vehicle {
abstract startEngine(): void;
abstract stopEngine(): void;
move(): void {
console.log('Vehicle is moving.');
}
}
abstract class Car extends Vehicle {
startEngine(): void {
console.log('Car engine started.');
}
// stopEngine not implemented
}
class Sedan extends Car {
stopEngine(): void {
console.log('Sedan engine stopped.');
}
}
const sedan = new Sedan();
sedan.startEngine(); // Outputs: Car engine started.
sedan.move(); // Outputs: Vehicle is moving.
sedan.stopEngine(); // Outputs: Sedan engine stopped.
Explanation:
Car is abstract because it doesn't implement all abstract methods from Vehicle.
Sedan implements the remaining stopEngine method, making it concrete.
Benefits:
Enforce Contracts: Abstract classes define methods that subclasses must implement.
Code Reuse: Common functionality can be implemented in the abstract class.
Type Safety: Provides a base type for derived classes.
Use Cases:
When you have a base class that shouldn't be instantiated on its own.
When you want to provide a common interface and shared code.
Differences from Interfaces:
Abstract Classes:
Can contain implementation (concrete methods).
Can have constructors, fields, and access modifiers.
Support single inheritance.
Interfaces:
Declaration-only, no implementation.
Cannot have constructors or fields.
Can be implemented by multiple classes (TypeScript supports multiple interfaces).
Conclusion:
The abstract keyword in TypeScript is a powerful tool for designing class hierarchies, enforcing method implementation, and sharing code among related classes, adhering to the OOP principles of abstraction and inheritance.
</question_item>
<question_item>
What are intersection types in TypeScript, and how do they differ from union types? Provide an example where an intersection type is useful, and explain the implications.
Intersection Types in TypeScript combine multiple types into one. An intersection type represents an object that has all the properties of the constituent types.
Syntax:T & U
Meaning: An object of type T & U must satisfy both T and U.
Contrast with Union Types:
Union Types (T | U):
The variable can be of type T or U.
Intersection Types (T & U):
The variable must be both T and U.
Example of Intersection Type:
Suppose you have two interfaces:
typescript
interface HasName {
name: string;
}
interface HasAge {
age: number;
}
type Person = HasName & HasAge;
const person: Person = {
name: 'Alice',
age: 30,
};
console.log(person.name); // Outputs: Alice
console.log(person.age); // Outputs: 30
Explanation:
Person is an intersection of HasName and HasAge.
An object of type Person must have both name and age properties.
Use Cases for Intersection Types:
Combining Multiple Interfaces:
Useful in mixin patterns or when composing different behaviors.
Example with Classes and Interfaces:
typescript
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
interface Loggable {
log(): void;
}
function applyMixins<T extends new (...args: any[]) => {}>(BaseClass: T, Mixin: any): T & Mixin {
Object.getOwnPropertyNames(Mixin.prototype).forEach(name => {
BaseClass.prototype[name] = Mixin.prototype[name];
});
return BaseClass as T & Mixin;
}
class Logger {
log() {
console.log('Logging...');
}
}
const PersonWithLogging = applyMixins(Person, Logger);
const person = new PersonWithLogging('Bob') as Person & Loggable;
person.log(); // Outputs: Logging...
console.log(person.name); // Outputs: Bob
Explanation:
PersonWithLogging combines Person and Logger.
The resulting object has properties and methods from both.
Type Guards with Intersection Types:
Sometimes intersection types can become never if there are no overlapping members.
Example:
typescript
type A = { a: string };
type B = { b: number };
type C = A & B;
const obj: C = { a: 'hello', b: 42 };
Implications:
Type Combination: Intersection types allow for the combination of multiple types into one.
Structural Typing: TypeScript uses structural typing; the object's shape is what matters.
Complexity: Be cautious with intersection types involving types with incompatible properties, as they might result in never types.
type IntersectionType = { a: string } & { b: number };
const intersectionObj: IntersectionType = { a: 'hello', b: 42 }; // Must have both properties
Conclusion:
Intersection types in TypeScript are valuable for combining multiple types into one, ensuring that a variable meets all specified requirements. They differ from union types, which allow a variable to be of any one of several types. Intersection types are particularly useful in advanced type manipulations, mixins, and ensuring comprehensive type constraints.
</question_item>
<question_item>
How does TypeScript's type inference work when extending generic classes? Provide an example where extending a generic class requires specifying type parameters, and explain how type inference aids or requires explicit annotations.
TypeScript's type inference tries to automatically infer the types of variables, functions, classes, etc., based on their usage. When extending generic classes, TypeScript may or may not be able to infer the generic type parameters, depending on how the subclass is declared.
Example:
typescript
class Collection<T> {
protected items: T[] = [];
add(item: T): void {
this.items.push(item);
}
get(index: number): T {
return this.items[index];
}
}
// Attempt to extend without specifying type parameters
class NumberCollection extends Collection<number> {
sum(): number {
return this.items.reduce((total, num) => total + num, 0);
}
}
Explanation:
Extending a Generic Class:
NumberCollection extends Collection<number>, specifying that T is number.
TypeScript needs to know what T is in NumberCollection to accurately type items.
Type Inference Aids:
When you explicitly specify type parameters during extension, TypeScript can infer types for properties and methods.
In methods like sum(), TypeScript knows this.items is number[].
Example with Inferred Generics:
If you try to inherit without specifying the type parameter:
typescript
class GenericCollection<T> extends Collection<T> {
// Additional methods
}
const stringCollection = new GenericCollection<string>();
stringCollection.add('Hello'); // TypeScript knows T is string
Type Inference Limitations:
If the subclass doesn't specify the type parameter and doesn't have its own type parameter, TypeScript cannot infer T.
Example Requiring Explicit Annotation:
typescript
class SpecificCollection extends Collection<number> {
// Must specify that T is number
}
const collection = new SpecificCollection();
collection.add(5); // Allowed
// collection.add('Hello'); // Error: Argument of type 'string' is not assignable to parameter of type 'number'
Using Type Parameters in Subclasses:
If the subclass is also generic:
typescript
class KeyValuePair<K, V> {
constructor(public key: K, public value: V) {}
}
class StringKeyDictionary<V> extends KeyValuePair<string, V> {
// V is inferred from usage or can be specified
}
const dict = new StringKeyDictionary<number>('age', 30);
// TypeScript infers V as number
Type Inference in Methods:
TypeScript can often infer the return type of methods without explicit annotations.
typescript
class Mapper<T, U> {
map(items: T[], fn: (item: T) => U): U[] {
return items.map(fn);
}
}
const mapper = new Mapper<number, string>();
const result = mapper.map([1, 2, 3], num => num.toString());
// result is string[]
Conclusion:
Type Inference Helps:
Reduces need for explicit type annotations.
Increases code readability.
Explicit Annotations Required:
When TypeScript cannot infer types, particularly in class extensions.
To clarify intention and prevent type errors.
Best Practices:
Specify type parameters when extending generic classes unless the subclass is also generic.
Use explicit types when inference is not sufficient.
Understanding how type inference works with generic classes in TypeScript is essential for writing accurate and maintainable generic code, ensuring that types are correctly propagated through class hierarchies.
</question_item>
<question_item>
What is a decorator factory in TypeScript, and how does it differ from a regular decorator? Provide an example of a decorator factory that accepts parameters and alters a class's behavior.
A Decorator Factory in TypeScript is a function that returns a decorator. It's used when you need to pass parameters to a decorator.
Difference from Regular Decorator:
Regular Decorator:
A function that is applied directly to the target (class, method, etc.).
Decorator Factory:
A function that returns a decorator function.
Allows passing arguments to customize the behavior.
Example of Decorator Factory:
Suppose we want to create a decorator that logs when an instance of a class is created, and we want to specify the message.
Decorator Factory Definition:
typescript
function LogInstanceCreation(message: string) {
return function <T extends { new (...args: any[]): {} }>(constructor: T) {
return class extends constructor {
constructor(...args: any[]) {
super(...args);
console.log(`${message}: ${JSON.stringify(args)}`);
}
};
};
}
Usage:
typescript
@LogInstanceCreation('Creating instance')
class Person {
constructor(public name: string, public age: number) {}
}
const person = new Person('Alice', 30);
// Outputs: Creating instance: ["Alice",30]
Explanation:
Decorator Factory LogInstanceCreation:
Accepts a message parameter.
Returns a class decorator.
Class Decorator:
Extends the original constructor.
Overrides the constructor to add logging behavior.
When Applied:
The decorator factory is called with 'Creating instance'.
The resulting decorator is then applied to the Person class.
Benefits of Decorator Factories:
Customization: Allows decorators to be configured with parameters.
Reusability: The same decorator factory can produce different decorators based on parameters.
Flexibility: Can be applied to various targets with different behaviors.
Another Example: Method Decorator Factory:
Suppose we want to create a method decorator that measures execution time and allows us to specify the units (milliseconds, seconds).
typescript
function MeasureExecutionTime(unit: 'ms' | 's' = 'ms') {
return function (
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const start = performance.now();
const result = originalMethod.apply(this, args);
const end = performance.now();
const duration = unit === 'ms' ? end - start : (end - start) / 1000;
console.log(`${String(propertyKey)} executed in ${duration} ${unit}`);
return result;
};
return descriptor;
};
}
class Calculator {
@MeasureExecutionTime('ms')
compute(num: number): number {
// Some heavy computation
let sum = 0;
for (let i = 0; i < num; i++) {
sum += i;
}
return sum;
}
}
const calc = new Calculator();
calc.compute(1000000);
// Outputs: compute executed in X ms
Explanation:
Decorator Factory MeasureExecutionTime:
Accepts a unit parameter to specify time measurement units.
Method Decorator:
Wraps the original method to measure execution time.
Logs the duration in the specified units.
Conclusion:
Decorator factories in TypeScript provide a powerful way to create configurable decorators by parameterizing them. They enhance decorators' flexibility, making them more versatile and suitable for various scenarios where behavior needs to be customized based on input parameters.
</question_item>
<question_item>
Explain how you can use TypeScript to implement the Observer design pattern. Provide an example where classes interact using the Observer pattern with appropriate interfaces or abstract classes.
The Observer Pattern is a behavioral design pattern that allows an object (the Subject) to maintain a list of dependents (the Observers) and notify them of state changes.
Implementing the Observer Pattern in TypeScript:
Define Observer Interface:
Declares the update method that subjects use to notify observers.
class ConcreteSubject implements Subject {
private observers: Observer[] = [];
private _state: number = 0;
get state(): number {
return this._state;
}
set state(value: number) {
this._state = value;
this.notify();
}
attach(observer: Observer): void {
const isExist = this.observers.includes(observer);
if (isExist) {
console.log('Observer already attached.');
return;
}
this.observers.push(observer);
console.log('Observer attached.');
}
detach(observer: Observer): void {
const observerIndex = this.observers.indexOf(observer);
if (observerIndex === -1) {
console.log('Observer not found.');
return;
}
this.observers.splice(observerIndex, 1);
console.log('Observer detached.');
}
notify(): void {
console.log('Notifying observers...');
for (const observer of this.observers) {
observer.update(this);
}
}
}
Concrete Observers:
typescript
class ConcreteObserverA implements Observer {
update(subject: Subject): void {
if ((subject as ConcreteSubject).state < 5) {
console.log('ConcreteObserverA: Reacted to the event.');
}
}
}
class ConcreteObserverB implements Observer {
update(subject: Subject): void {
if ((subject as ConcreteSubject).state >= 5) {
console.log('ConcreteObserverB: Reacted to the event.');
}
}
}
Usage:
typescript
const subject = new ConcreteSubject();
const observerA = new ConcreteObserverA();
subject.attach(observerA);
const observerB = new ConcreteObserverB();
subject.attach(observerB);
subject.state = 2;
// Outputs:
// Notifying observers...
// ConcreteObserverA: Reacted to the event.
subject.state = 7;
// Outputs:
// Notifying observers...
// ConcreteObserverB: Reacted to the event.
Explanation:
Subject (ConcreteSubject):
Manages a list of observers.
Notifies observers when its state changes.
Observers (ConcreteObserverA, ConcreteObserverB):
Implement the update method.
React based on the subject's state.
Interaction:
Observers register with the subject.
When the subject's state changes, it calls notify, which invokes update on each observer.
Benefits:
Decoupling: Subject and observers are loosely coupled.
Flexibility: Observers can be added/removed at runtime.
Reusability: Observers can be reused with different subjects.
By using TypeScript's interfaces and classes, you can effectively implement the Observer pattern, ensuring type safety and clear contracts between subjects and observers. This pattern is useful in scenarios where changes in one object need to be communicated to many other objects, such as in event handling systems or data binding in UI frameworks.
</question_item>
</question_list>