Lab 02: Generics

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Master generic functions, classes, interfaces, constraints, and TypeScript's built-in utility types.


Step 1: Setup

docker run -it --rm node:20-alpine sh
npm install -g typescript ts-node
mkdir /lab02 && cd /lab02
cat > tsconfig.json << 'EOF'
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true
  }
}
EOF

Step 2: Generic Functions

💡 TypeScript can usually infer generic types from arguments — you don't always need <T> explicitly.


Step 3: Generic Classes


Step 4: Generic Interfaces and Constraints

💡 extends keyof T constrains K to valid property names of T — prevents runtime undefined access.


Step 5: Default Type Parameters


Step 6: Built-in Utility Types


Step 7: Generic Constraints in Practice


Step 8: Capstone — Generic Repository

Run:

📸 Verified Output:


Summary

Concept
Syntax
Use Case

Generic function

function f<T>(x: T): T

Reusable typed functions

Generic class

class Stack<T>

Typed data structures

Constraint

T extends HasId

Require specific shape

keyof constraint

K extends keyof T

Safe property access

Default type

<T = unknown>

Fallback type

Partial

Partial<T>

All optional

Pick/Omit

Pick<T, K> / Omit<T, K>

Select/exclude fields

ReturnType

ReturnType<typeof fn>

Infer function return type

Last updated