TypeScript
Beginner
1 min read
Generics in Classes and Static Members
Example
// Generic Stack class
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
peek(): T | undefined { return this.items[this.items.length - 1]; }
get size(): number { return this.items.length; }
isEmpty(): boolean { return this.items.length === 0; }
}
const numStack = new Stack<number>();
numStack.push(1);
numStack.push(2);
console.log(numStack.peek()); // 2
console.log(numStack.pop()); // 2
// Static members — counter shared across instances
class IdGenerator {
private static nextId = 1;
static generate(): number {
return IdGenerator.nextId++;
}
static reset(): void {
IdGenerator.nextId = 1;
}
}
console.log(IdGenerator.generate()); // 1
console.log(IdGenerator.generate()); // 2
// Mixin pattern
type Constructor<T = {}> = new (...args: unknown[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
createdAt = new Date();
updatedAt = new Date();
touch() { this.updatedAt = new Date(); }
};
}
class BaseModel { constructor(public id: number) {} }
const TimestampedModel = Timestamped(BaseModel);
const record = new TimestampedModel(1);
console.log(record.createdAt instanceof Date); // true
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript