JavaScript and TypeScript course ยท Module 10: TypeScript in Practice
TypeScript with Popular Frameworks
In this lesson5
"Welcome back to Jurassic Park " says Dr. Rex. "You already know TypeScript as a standalone language, but in the real world we rarely use it on its own. We usually combine it with frameworks that help build complex applications." Without types, a typo in a prop name shows up only when the Velociraptor card displays the label Safe.
TypeScript with React - Typed Components
React is one of the most popular libraries for building user interfaces. TypeScript integrates with it very well, providing strong typing for components, props and hooks.
Basic Functional Components
You describe props with an interface in which the ? sign marks an optional field, and the component gets the type React.FC<DinoCardProps>:
// Interface for component props
interface DinoCardProps {
name: string;
species: string;
isDangerous: boolean;
age?: number; // Optional field
onEscape?: () => void; // Optional callback function
}
// Functional component with typed props
const DinoCard: React.FC<DinoCardProps> = ({
name,
species,
isDangerous,
age,
onEscape
}) => {
return (
<div className="dino-card">
<h2>{name}</h2>
<p>Species: {species}</p>
<p>Age: {age || 'Unknown'}</p>
<div className={isDangerous ? 'danger' : 'safe'}>
{isDangerous ? 'DANGEROUS' : 'Safe'}
</div>
{onEscape && (
<button onClick={onEscape}>
Report escape
</button>
)}
</div>
);
};
// Usage with full typing
const App = () => {
const handleEscape = () => {
console.log('ALARM: Dinosaur escaped!');
};
return (
<DinoCard
name="Blue"
species="Velociraptor"
isDangerous={true}
age={4}
onEscape={handleEscape}
/>
);
};A missing species prop is a compilation error right in App. Many teams write simply function DinoCard(props: DinoCardProps) instead of React.FC, because since React 18 both forms work practically the same. For numbers, ?? is better than ||, because an age of 0 is valid too.
Typing React Hooks
Hooks are generic. For simple values TypeScript infers the type by itself, but for an empty array or null you provide it in angle brackets:
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
interface Dinosaur {
id: number;
name: string;
species: string;
status: 'contained' | 'escaped' | 'feeding';
}
const DinosaurMonitor: React.FC = () => {
// useState with type
const [dinosaurs, setDinosaurs] = useState<Dinosaur[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<Error | null>(null);
// useRef with DOM element type
const alertSound = useRef<HTMLAudioElement>(null);
// useEffect - fetching data
useEffect(() => {
const fetchDinosaurs = async () => {
setLoading(true);
try {
const response = await fetch('/api/dinosaurs');
const data: Dinosaur[] = await response.json();
setDinosaurs(data);
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
}
};
fetchDinosaurs();
}, []);
// useCallback with typed parameters
const handleDinoEscape = useCallback((dinoId: number) => {
setDinosaurs(prev =>
prev.map(dino =>
dino.id === dinoId
? { ...dino, status: 'escaped' as const }
: dino
)
);
// Play alarm
if (alertSound.current) {
alertSound.current.play();
}
}, []);
// useMemo with return type
const dangerousDinos = useMemo<Dinosaur[]>(() => {
return dinosaurs.filter(dino => dino.status === 'escaped');
}, [dinosaurs]);
if (loading) return <div>Loading monitoring data...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>Dinosaur Monitor</h1>
<audio ref={alertSound} src="/sounds/alarm.mp3" />
{dangerousDinos.length > 0 && (
<div className="alert">
WARNING: {dangerousDinos.length} dinosaurs at large!
</div>
)}
<div className="dino-grid">
{dinosaurs.map(dino => (
<DinoCard
key={dino.id}
name={dino.name}
species={dino.species}
isDangerous={dino.status === 'escaped'}
onEscape={() => handleDinoEscape(dino.id)}
/>
))}
</div>
</div>
);
};Without <Dinosaur[]>, the empty array would have the type never[] and you could not add anything to it. useRef<HTMLAudioElement>(null) knows that current is an audio element or null, so the code checks it before play(), and as const keeps the literal 'escaped' instead of widening it to string.
Custom Hooks with TypeScript
A custom hook returns an object described by an interface, so the component gets autocomplete for every function. Omit<Dinosaur, 'id'> means a dinosaur without the id, which the server assigns:
// Custom hook for managing a list of dinosaurs
interface UseDinosaursResult {
dinosaurs: Dinosaur[];
loading: boolean;
error: Error | null;
addDinosaur: (dino: Omit<Dinosaur, 'id'>) => Promise<void>;
removeDinosaur: (id: number) => Promise<void>;
updateStatus: (id: number, status: Dinosaur['status']) => void;
}
function useDinosaurs(): UseDinosaursResult {
const [dinosaurs, setDinosaurs] = useState<Dinosaur[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<Error | null>(null);
const addDinosaur = useCallback(async (dino: Omit<Dinosaur, 'id'>) => {
setLoading(true);
try {
const response = await fetch('/api/dinosaurs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(dino)
});
const newDino: Dinosaur = await response.json();
setDinosaurs(prev => [...prev, newDino]);
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
}
}, []);
const removeDinosaur = useCallback(async (id: number) => {
setLoading(true);
try {
await fetch(`/api/dinosaurs/${id}`, { method: 'DELETE' });
setDinosaurs(prev => prev.filter(d => d.id !== id));
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
}
}, []);
const updateStatus = useCallback((id: number, status: Dinosaur['status']) => {
setDinosaurs(prev =>
prev.map(dino =>
dino.id === id ? { ...dino, status } : dino
)
);
}, []);
return {
dinosaurs,
loading,
error,
addDinosaur,
removeDinosaur,
updateStatus
};
}
// Using the custom hook
const ParkManager: React.FC = () => {
const {
dinosaurs,
loading,
error,
addDinosaur,
updateStatus
} = useDinosaurs();
const handleFeedDino = (id: number) => {
updateStatus(id, 'feeding');
setTimeout(() => updateStatus(id, 'contained'), 5000);
};
return (
<div>
{/* Component using the hook */}
</div>
);
};Dinosaur['status'] makes sure that updateStatus accepts only one of the three statuses.
TypeScript with Node.js/Express - Backend API
Typing Express Applications
On the server side you type requests, responses and middleware, and a controller groups the handlers of a single resource:
import express, { Request, Response, NextFunction } from 'express';
// Interfaces for data models
interface Dinosaur {
id: number;
name: string;
species: string;
paddock: number;
feedingSchedule: string[];
}
interface CreateDinosaurDTO {
name: string;
species: string;
paddock: number;
}
// Extending Request with custom fields
interface AuthRequest extends Request {
user?: {
id: number;
role: 'admin' | 'keeper' | 'visitor';
};
}
// Controller with typing
class DinosaurController {
// GET /api/dinosaurs
async getAll(req: Request, res: Response<Dinosaur[]>, next: NextFunction) {
try {
const dinosaurs = await this.dinosaurService.findAll();
res.json(dinosaurs);
} catch (error) {
next(error);
}
}
// GET /api/dinosaurs/:id
async getById(
req: Request<{ id: string }>,
res: Response<Dinosaur>,
next: NextFunction
) {
try {
const id = parseInt(req.params.id);
const dinosaur = await this.dinosaurService.findById(id);
if (!dinosaur) {
res.status(404).json({ error: 'Dinosaur not found' } as any);
return;
}
res.json(dinosaur);
} catch (error) {
next(error);
}
}
// POST /api/dinosaurs
async create(
req: Request<{}, {}, CreateDinosaurDTO>,
res: Response<Dinosaur>,
next: NextFunction
) {
try {
const newDino = await this.dinosaurService.create(req.body);
res.status(201).json(newDino);
} catch (error) {
next(error);
}
}
}
// Middleware with typing
const authenticateUser = (
req: AuthRequest,
res: Response,
next: NextFunction
): void => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
res.status(401).json({ error: 'No token provided' });
return;
}
try {
const decoded = verifyToken(token);
req.user = decoded;
next();
} catch (error) {
res.status(401).json({ error: 'Invalid token' });
}
};
// Routing
const app = express();
app.use(express.json());
const dinoController = new DinosaurController();
app.get('/api/dinosaurs', dinoController.getAll.bind(dinoController));
app.get('/api/dinosaurs/:id', dinoController.getById.bind(dinoController));
app.post('/api/dinosaurs', authenticateUser, dinoController.create.bind(dinoController));bind(dinoController) is necessary, because a method passed as a callback loses this. The this.dinosaurService field still has to be declared and injected through the constructor, and instead of the AuthRequest interface you can use the express-serve-static-core augmentation from the previous lesson.
Typed Services and Repositories
The Repository pattern hides the database behind the generic Repository<T> interface, and the service contains business logic such as validation:
// Repository Pattern with TypeScript
interface Repository<T> {
findAll(): Promise<T[]>;
findById(id: number): Promise<T | null>;
create(data: Omit<T, 'id'>): Promise<T>;
update(id: number, data: Partial<T>): Promise<T>;
delete(id: number): Promise<void>;
}
class DinosaurRepository implements Repository<Dinosaur> {
async findAll(): Promise<Dinosaur[]> {
// Database implementation
return [];
}
async findById(id: number): Promise<Dinosaur | null> {
// Implementation
return null;
}
async create(data: Omit<Dinosaur, 'id'>): Promise<Dinosaur> {
// Implementation
return { id: 1, ...data } as Dinosaur;
}
async update(id: number, data: Partial<Dinosaur>): Promise<Dinosaur> {
// Implementation
return {} as Dinosaur;
}
async delete(id: number): Promise<void> {
// Implementation
}
}
// Service Layer
class DinosaurService {
constructor(private repository: DinosaurRepository) {}
async getAllDinosaurs(): Promise<Dinosaur[]> {
return this.repository.findAll();
}
async getDinosaurById(id: number): Promise<Dinosaur> {
const dino = await this.repository.findById(id);
if (!dino) {
throw new Error(`Dinosaur with id ${id} not found`);
}
return dino;
}
async createDinosaur(data: CreateDinosaurDTO): Promise<Dinosaur> {
// Validation
this.validateDinosaurData(data);
// Creation
return this.repository.create({
...data,
feedingSchedule: this.generateFeedingSchedule(data.species)
});
}
private validateDinosaurData(data: CreateDinosaurDTO): void {
if (!data.name || data.name.length < 2) {
throw new Error('Invalid dinosaur name');
}
if (data.paddock < 1 || data.paddock > 10) {
throw new Error('Invalid paddock number');
}
}
private generateFeedingSchedule(species: string): string[] {
// Schedule generation logic
return ['08:00', '14:00', '20:00'];
}
}The service depends on the concrete DinosaurRepository class, while according to the dependency inversion principle it is better to accept Repository<Dinosaur> and pass an in-memory repository in tests. Partial<T> works only on the first level, so for nested objects you write a recursive DeepPartial<T>, and the built-in NonNullable<T> removes null and undefined from a type.
TypeScript with Next.js - Full-stack with Native Support
Next.js has built-in TypeScript support: just create a .ts or .tsx file, and Next.js configures the compiler and creates tsconfig.json by itself.
Pages and API Routes
In the Pages Router a page gets the type NextPage<Props>, and the data fetching function the type GetServerSideProps<Props>, so the page props and the server data have to match:
// pages/dinosaurs/[id].tsx - Dynamic route with typing
import { GetServerSideProps, NextPage } from 'next';
interface DinosaurPageProps {
dinosaur: Dinosaur;
lastUpdated: string;
}
// Page component
const DinosaurPage: NextPage<DinosaurPageProps> = ({ dinosaur, lastUpdated }) => {
return (
<div>
<h1>{dinosaur.name}</h1>
<p>Species: {dinosaur.species}</p>
<p>Paddock: {dinosaur.paddock}</p>
<small>Last updated: {lastUpdated}</small>
</div>
);
};
// Server-side rendering with typing
export const getServerSideProps: GetServerSideProps<DinosaurPageProps> = async (context) => {
const { id } = context.params as { id: string };
try {
const response = await fetch(`https://api.park.com/dinosaurs/${id}`);
const dinosaur: Dinosaur = await response.json();
return {
props: {
dinosaur,
lastUpdated: new Date().toISOString()
}
};
} catch (error) {
return {
notFound: true
};
}
};
export default DinosaurPage;If getServerSideProps returns an object without lastUpdated, the compiler reports an error before the page reaches the visitors.
API Routes in Next.js
An API route in the Pages Router is a function with the types NextApiRequest and NextApiResponse<T>, where T describes the shape of the response:
// pages/api/dinosaurs/[id].ts
import type { NextApiRequest, NextApiResponse } from 'next';
type ResponseData = {
dinosaur?: Dinosaur;
error?: string;
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
const { id } = req.query;
if (req.method === 'GET') {
try {
const dinosaur = await getDinosaurById(Number(id));
res.status(200).json({ dinosaur });
} catch (error) {
res.status(404).json({ error: 'Dinosaur not found' });
}
} else if (req.method === 'PUT') {
try {
const updatedDino = await updateDinosaur(Number(id), req.body);
res.status(200).json({ dinosaur: updatedDino });
} catch (error) {
res.status(400).json({ error: 'Update failed' });
}
} else {
res.status(405).json({ error: 'Method not allowed' });
}
}req.query.id has the type string | string[] | undefined, which is why the code converts it to a number, and an unsupported method gets status 405.
App Router (Next.js 13+) with Server Components
In the App Router a page is a Server Component by default, which can be an async function and fetch data directly. You move interactive parts into Client Components:
// app/dinosaurs/[id]/page.tsx
// Since Next.js 15, params and searchParams are Promise objects
interface PageProps {
params: Promise<{ id: string }>;
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}
// Server Component
export default async function DinosaurDetailPage({ params }: PageProps) {
const { id } = await params;
const dinosaur = await getDinosaurById(id);
return (
<div>
<h1>{dinosaur.name}</h1>
<DinosaurDetails dino={dinosaur} />
</div>
);
}
// Client Component - a separate file, e.g. app/dinosaurs/[id]/DinosaurDetails.tsx,
// because the 'use client' directive must be at the very top of the file
'use client';
interface DinosaurDetailsProps {
dino: Dinosaur;
}
export function DinosaurDetails({ dino }: DinosaurDetailsProps) {
const [isFavorite, setIsFavorite] = useState(false);
return (
<div>
<button onClick={() => setIsFavorite(!isFavorite)}>
{isFavorite ? 'Favorited' : 'Add to favorites'}
</button>
{/* Rest of the component */}
</div>
);
}Since Next.js 15, params is a Promise object, so you await it first, while in versions 13 and 14 it was a plain object. The 'use client' directive must stand at the top of a separate file, which is why DinosaurDetails lives in its own module.
Typing Patterns in Frameworks
Generic Components
A generic component works for any item type, and TypeScript makes sure that renderItem and keyExtractor match the array you pass in:
// Universal list component with typing
interface ListProps<T> {
items: T[];
renderItem: (item: T, index: number) => React.ReactNode;
keyExtractor: (item: T) => string | number;
emptyMessage?: string;
}
function List<T>({ items, renderItem, keyExtractor, emptyMessage }: ListProps<T>) {
if (items.length === 0) {
return <div>{emptyMessage || 'No items'}</div>;
}
return (
<ul>
{items.map((item, index) => (
<li key={keyExtractor(item)}>
{renderItem(item, index)}
</li>
))}
</ul>
);
}
// Usage
const DinosaurList = () => {
const dinosaurs: Dinosaur[] = [
{ id: 1, name: 'Rex', species: 'T-Rex', paddock: 1, feedingSchedule: [] },
{ id: 2, name: 'Blue', species: 'Velociraptor', paddock: 3, feedingSchedule: [] }
];
return (
<List<Dinosaur>
items={dinosaurs}
keyExtractor={(dino) => dino.id}
renderItem={(dino) => (
<div>
<strong>{dino.name}</strong> - {dino.species}
</div>
)}
emptyMessage="No dinosaurs in the system"
/>
);
};Writing List<Dinosaur> in JSX states the type explicitly, although TypeScript would infer it from items, and the same component can also display a list of paddocks.
Form Handling with TypeScript
The react-hook-form library takes the type of the form data, so register accepts only existing field names:
import { useForm, SubmitHandler } from 'react-hook-form';
interface DinosaurFormData {
name: string;
species: string;
paddock: number;
isDangerous: boolean;
feedingTimes: string[];
}
const DinosaurForm: React.FC = () => {
const {
register,
handleSubmit,
formState: { errors }
} = useForm<DinosaurFormData>();
const onSubmit: SubmitHandler<DinosaurFormData> = async (data) => {
try {
const response = await fetch('/api/dinosaurs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (response.ok) {
alert('Dinosaur added!');
}
} catch (error) {
console.error('Error adding dinosaur:', error);
}
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...register('name', { required: 'Name is required' })}
placeholder="Dinosaur name"
/>
{errors.name && <span>{errors.name.message}</span>}
<input
{...register('species', { required: true })}
placeholder="Species"
/>
<input
type="number"
{...register('paddock', {
required: true,
min: 1,
max: 10,
valueAsNumber: true // without it, the value of a number input is a string
})}
placeholder="Paddock number"
/>
<label>
<input type="checkbox" {...register('isDangerous')} />
Dangerous species
</label>
<button type="submit">Add dinosaur</button>
</form>
);
};A typo in a field name is a compilation error. A type="number" field returns a string in the browser, which is why the valueAsNumber option converts it to a number that matches the paddock: number type.
Summary
"You see?" Dr. Rex smiles. "TypeScript integrates great with popular frameworks."
React
- Strong component typing through
React.FC<Props> - Typed hooks (
useState<T>,useRef<HTMLElement>) - Custom hooks with full type safety
- Generic components for reusability
Node.js/Express
- Typing Request, Response, NextFunction
- Repository and Service patterns with interfaces
- Middleware with custom Request types
- DTOs (Data Transfer Objects) describing input data
Next.js
- Native TypeScript support without manual configuration
- Typed
getServerSidePropsandgetStaticProps - API Routes with typing
- Server and Client Components in the App Router
The key benefits are catching errors while you write the code, autocomplete (IntelliSense), fearless refactoring, self-documenting code and easier teamwork. Start new projects in TypeScript with strict mode right away because adding types to a finished application costs more. In the next lesson you will combine the knowledge from the whole module in the final project: the park diagnostic system.
"TypeScript is a safeguard for the park systems that takes a bit of work at first but saves a lot of trouble in the long run," concludes Dr. Rex.
Code for this lesson: index.js
// Memory profiling - find and fix memory leaks
console.log("Jurassic Park - Memory Profiling Lab");
console.log("Find and fix memory leaks in the code!\n");
// ====================================
// TASK: The code below has several memory leaks.
// Fix them by applying good practices.
// ====================================
// LEAK 1: Event listeners without cleanup
// Fix: Add a destroy() method with removeEventListener
class DinosaurTracker {
constructor(name) {
this.name = name;
this.positions = [];
this.handler = this.onPositionUpdate.bind(this);
// addEventListener simulation
console.log(`Tracker for ${name} - listener added`);
}
onPositionUpdate(position) {
this.positions.push(position);
}
// TODO: Add a destroy() method that removes the event listener
destroy() {
// Solution: removing the listener
// removeEventListener('position', this.handler);
this.positions = [];
this.handler = null;
console.log(`Tracker for ${this.name} - listener removed, memory freed`);
}
}
// LEAK 2: Growing array without a limit
// Fix: Limit the array size
class AlertSystem {
constructor() {
this.alerts = [];
this.maxAlerts = 100; // TODO: Set the limit
}
addAlert(message) {
// TODO: Check the limit and remove the oldest alerts
if (this.alerts.length >= this.maxAlerts) {
this.alerts.shift(); // Remove the oldest one
}
this.alerts.push({
message,
timestamp: Date.now()
});
}
getAlertCount() {
return this.alerts.length;
}
}
// LEAK 3: Forgotten timers
// Fix: Add cleanup for the timers
class HealthMonitor {
constructor() {
this.timers = [];
this.data = [];
}
startMonitoring(dinoName, intervalMs) {
const timer = setInterval(() => {
this.data.push({
dino: dinoName,
health: Math.random() * 100,
time: Date.now()
});
}, intervalMs);
this.timers.push(timer);
console.log(`Monitoring ${dinoName} started`);
}
// TODO: Add a stopAll() method that clears the timers
stopAll() {
this.timers.forEach(timer => clearInterval(timer));
this.timers = [];
this.data = [];
console.log("All monitors stopped, timers cleared");
}
}
// LEAK 4: Circular references
// Fix: Use WeakRef or WeakMap
class Enclosure {
constructor(name) {
this.name = name;
this.dinosaurs = [];
}
addDinosaur(dino) {
this.dinosaurs.push(dino);
// Circular reference: dino -> enclosure -> dino
dino.enclosure = this;
}
}
// Solution with WeakRef
class EnclosureFixed {
constructor(name) {
this.name = name;
this.dinosaurs = new Set();
}
addDinosaur(dino) {
this.dinosaurs.add(dino);
// WeakRef does not block garbage collection
dino.enclosureRef = new WeakRef(this);
}
removeDinosaur(dino) {
this.dinosaurs.delete(dino);
dino.enclosureRef = null;
}
}
// ====================================
// TESTY
// ====================================
console.log("=== Testing the fixed leaks ===\n");
// Test 1: Tracker with cleanup
const tracker = new DinosaurTracker("T-Rex");
tracker.onPositionUpdate({ x: 10, y: 20 });
tracker.onPositionUpdate({ x: 15, y: 25 });
console.log("Positions before destroy:", tracker.positions.length);
tracker.destroy();
console.log("Positions after destroy:", tracker.positions.length);
// Test 2: Alert system with a limit
console.log("\n--- Alert System ---");
const alertSys = new AlertSystem();
for (let i = 0; i < 150; i++) {
alertSys.addAlert(`Alert #${i}`);
}
console.log(`Alerts after 150 additions (limit 100): ${alertSys.getAlertCount()}`);
// Test 3: Health monitor with cleanup
console.log("\n--- Health Monitor ---");
const healthMon = new HealthMonitor();
healthMon.startMonitoring("Velociraptor", 1000);
healthMon.startMonitoring("Stegosaurus", 2000);
console.log("Active timers:", healthMon.timers.length);
healthMon.stopAll();
console.log("Timers after stopAll:", healthMon.timers.length);
// Test 4: WeakRef solution
console.log("\n--- Enclosure with WeakRef ---");
const enclosure = new EnclosureFixed("Paddock A");
let dino = { name: "Raptor", species: "Velociraptor" };
enclosure.addDinosaur(dino);
console.log("Dinosaur in enclosure:", enclosure.dinosaurs.size);
const encRef = dino.enclosureRef.deref();
console.log("Enclosure via WeakRef:", encRef ? encRef.name : "GC collected");
console.log("\nAll memory leaks fixed!");
console.log("Good practices:");
console.log("1. Always remove event listeners (destroy/cleanup)");
console.log("2. Limit array sizes (ring buffer / maxSize)");
console.log("3. Clear timers (clearInterval/clearTimeout)");
console.log("4. Use WeakRef/WeakMap for circular references");Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Code editor
Implement DeepPartial and NonNullable.