Day 2 – Interfaces Generics and Classes
Today's Focus
Model a domain with interfaces, type aliases, and generics; implement classes with OOP patterns.
Tasks
- Design typed domain models for a small e-commerce domain:
Product,CartItem,Order,Customer. Useinterfacefor object shapes andtypefor unions/aliases. Explain in a comment when you would chooseinterfaceovertypeand vice versa. - Write a generic
Result<T, E>type (similar to Rust's Result) with{ ok: true; value: T }and{ ok: false; error: E }variants. Write asafeParseIntfunction that returnsResult<number, string>. Use exhaustiveif/elseon the discriminant to make TypeScript narrow the type in each branch. - Implement a generic
Stack<T>class withpush(item: T),pop(): T | undefined,peek(): T | undefined, andisEmpty(): booleanmethods. Write a second classBoundedStack<T>that extendsStack<T>and rejects pushes when full. - Use TypeScript utility types: apply
Partial<Order>for an update function parameter,Readonly<Product>for a catalogue entry,Pick<Customer, "id" | "email">for a public profile type. Write a function that uses each. - Add
readonlymodifiers to properties that should not change after construction. Verify that attempting to mutate them causes a compile error.
Reading / Reference
- TypeScript Handbook: Interfaces, Generics, Classes.
- TypeScript Handbook: Utility Types.
- Effective TypeScript by Dan Vanderkam — Items 1–10 cover the mental model you need this week.