TExcelTAD
Home › TypeScript › TypeScript Exercises

TypeScript Exercises

Time to practise! Each exercise has a starter playground that already type-checks and runs, printing a placeholder result. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. Half of the challenge is the types: try to finish each exercise without using any or as casts. If you get stuck, open the solution — but give it a few minutes first.

# Exercise Topics
1 Score statistics functions, arrays, return types
2 In-stock report interfaces, optional properties
3 Format an ID union types, narrowing
4 Traffic light literal types, Record
5 Group by generics, keyof
6 Shape areas discriminated unions, exhaustiveness
7 Safe update Partial, Readonly, Omit
8 Generic stack classes, generics, private
9 Parallel loading async, Promise.all

1. Score statistics

Write stats(scores) that returns an object with the min, max and average of a non-empty array of numbers. Give the function an explicit return type.

Expected: { min: 55, max: 98, average: 79 }

ts · try it yourself
// TODO: add a return type and compute the real values
function stats(scores: number[]) {
  return { min: 0, max: 0, average: 0 };
}

console.log(stats([72, 98, 55, 91]));
{ min: 0, max: 0, average: 0 }
Show solution
ts
interface Stats {
  min: number;
  max: number;
  average: number;
}

function stats(scores: number[]): Stats {
  const sum = scores.reduce((acc, s) => acc + s, 0);
  return {
    min: Math.min(...scores),
    max: Math.max(...scores),
    average: sum / scores.length,
  };
}

console.log(stats([72, 98, 55, 91]));

2. In-stock report

Define a Product interface with title (string), price (number) and an optional stock (number). Write inStock(products) that returns the titles of products whose stock is greater than 0. A missing stock counts as 0.

Expected: [ 'Notebook', 'Pen' ]

ts · try it yourself
// TODO: define the Product interface
type Product = unknown;

function inStock(products: Product[]): string[] {
  // TODO: filter and map
  return [];
}

const products = [
  { title: "Notebook", price: 2.5, stock: 12 },
  { title: "Lamp", price: 19, stock: 0 },
  { title: "Pen", price: 1.2, stock: 40 },
  { title: "Globe", price: 35 },
];
console.log(inStock(products));
[]
Show solution
ts
interface Product {
  title: string;
  price: number;
  stock?: number;
}

function inStock(products: Product[]): string[] {
  return products.filter((p) => (p.stock ?? 0) > 0).map((p) => p.title);
}

3. Format an ID

formatId receives either a number or a string. Numbers must be padded with zeros to 6 digits and prefixed with #; strings must be trimmed and upper-cased.

Expected:

#000042
AB-77
ts · try it yourself
function formatId(id: number | string): string {
  // TODO: narrow with typeof
  return String(id);
}

console.log(formatId(42));
console.log(formatId("  ab-77 "));
42
  ab-77 
Show solution
ts
function formatId(id: number | string): string {
  if (typeof id === "number") {
    return "#" + String(id).padStart(6, "0");
  }
  return id.trim().toUpperCase();
}

4. Traffic light

Create a literal union type Light with "red", "green" and "yellow". Use a Record<Light, Light> to write next(light) (red → green → yellow → red), and a Record<Light, number> for how many seconds each light stays on (red 30, green 25, yellow 5).

Expected:

red 30s -> green
green 25s -> yellow
yellow 5s -> red
ts · try it yourself
// TODO: replace string with a literal union
type Light = string;

function next(light: Light): Light {
  return light; // TODO: use a Record lookup
}

const seconds = (light: Light): number => 0; // TODO

for (const l of ["red", "green", "yellow"] as Light[]) {
  console.log(`${l} ${seconds(l)}s -> ${next(l)}`);
}
red 0s -> red
green 0s -> green
yellow 0s -> yellow
Show solution
ts
type Light = "red" | "green" | "yellow";

const NEXT: Record<Light, Light> = { red: "green", green: "yellow", yellow: "red" };
const DURATION: Record<Light, number> = { red: 30, green: 25, yellow: 5 };

function next(light: Light): Light {
  return NEXT[light];
}

const seconds = (light: Light): number => DURATION[light];

const lights: Light[] = ["red", "green", "yellow"];
for (const l of lights) {
  console.log(`${l} ${seconds(l)}s -> ${next(l)}`);
}

5. Group by

Write a generic groupBy(items, key) that groups an array of objects by the value of one of their properties. The key parameter must only accept real property names of the item type, so groupBy(people, "agee") would be a compile error.

Expected: { Hanoi: [ 'Linh', 'Bao' ], Hue: [ 'Thu' ] } when printing the names per city.

ts · try it yourself
// TODO: make this generic: T for the item, K extends keyof T for the key
function groupBy(items: any[], key: string): Record<string, any[]> {
  return {};
}

const people = [
  { firstName: "Linh", city: "Hanoi", age: 31 },
  { firstName: "Thu", city: "Hue", age: 27 },
  { firstName: "Bao", city: "Hanoi", age: 45 },
];

const byCity = groupBy(people, "city");
const names = Object.fromEntries(
  Object.entries(byCity).map(([city, list]) => [city, list.map((p) => p.firstName)])
);
console.log(names);
{}
Show solution
ts
function groupBy<T, K extends keyof T>(items: T[], key: K): Record<string, T[]> {
  const groups: Record<string, T[]> = {};
  for (const item of items) {
    const group = String(item[key]);
    (groups[group] ??= []).push(item);
  }
  return groups;
}

With this signature list is typed as { firstName: string; city: string; age: number }[], so p.firstName is checked too.

6. Shape areas

Complete area for the discriminated union below and add an exhaustiveness check in the default branch, so adding a new shape later causes a compile error. Round the total to 2 decimals.

Expected: total area: 41.57

ts · try it yourself
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rect"; width: number; height: number }
  | { kind: "triangle"; base: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return 0; // TODO
    default:
      return 0; // TODO: handle the other kinds + exhaustive check
  }
}

const shapes: Shape[] = [
  { kind: "circle", radius: 2 },
  { kind: "rect", width: 4, height: 5 },
  { kind: "triangle", base: 6, height: 3 },
];
const total = shapes.reduce((sum, s) => sum + area(s), 0);
console.log(`total area: ${total.toFixed(2)}`);
total area: 0.00
Show solution
ts
function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "rect":
      return shape.width * shape.height;
    case "triangle":
      return (shape.base * shape.height) / 2;
    default: {
      const unreachable: never = shape;
      throw new Error(`unknown shape ${JSON.stringify(unreachable)}`);
    }
  }
}

7. Safe update

A User has a readonly id. Write updateUser(user, changes) that returns a new user with the changes applied. changes may contain any subset of the fields — except id, which must not be changeable at all (use Partial and Omit).

Expected:

{ id: 1, email: 'an@example.com', role: 'admin', active: true }
{ id: 1, email: 'an@example.com', role: 'viewer', active: true }
ts · try it yourself
interface User {
  readonly id: number;
  email: string;
  role: "admin" | "editor" | "viewer";
  active: boolean;
}

// TODO: give `changes` a proper type and return the merged user
function updateUser(user: User, changes: object): User {
  return user;
}

const an: User = { id: 1, email: "an@example.com", role: "viewer", active: true };
const promoted = updateUser(an, { role: "admin" });
console.log(promoted);
console.log(an);
{ id: 1, email: 'an@example.com', role: 'viewer', active: true }
{ id: 1, email: 'an@example.com', role: 'viewer', active: true }
Show solution
ts
type UserChanges = Partial<Omit<User, "id">>;

function updateUser(user: User, changes: UserChanges): User {
  return { ...user, ...changes };
}

// updateUser(an, { id: 2 }) is now a compile error:
// Object literal may only specify known properties, and 'id' does not exist in type 'UserChanges'.

8. Generic stack

Implement a Stack<T> class with a private array and the methods push(item), pop() (returns T | undefined), peek() and a size getter.

Expected:

size 3, top: c
c b
size 1
ts · try it yourself
class Stack {
  // TODO: make the class generic and implement the methods
  push(item: string) {}
  pop(): string | undefined { return undefined; }
  peek(): string | undefined { return undefined; }
  get size() { return 0; }
}

const s = new Stack();
s.push("a"); s.push("b"); s.push("c");
console.log(`size ${s.size}, top: ${s.peek()}`);
console.log(s.pop(), s.pop());
console.log(`size ${s.size}`);
size 0, top: undefined
undefined undefined
size 0
Show solution
ts
class Stack<T> {
  #items: T[] = [];

  push(item: T): void {
    this.#items.push(item);
  }

  pop(): T | undefined {
    return this.#items.pop();
  }

  peek(): T | undefined {
    return this.#items.at(-1);
  }

  get size(): number {
    return this.#items.length;
  }
}

const s = new Stack<string>();

9. Parallel loading

loadProfile and loadPosts simulate slow requests. Write loadDashboard(userId) that runs both in parallel and returns { profile, postCount }. Let TypeScript infer the types from Promise.all.

Expected: { profile: { id: 5, handle: '@user5' }, postCount: 3 }

ts · try it yourself
const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));

async function loadProfile(id: number) {
  await wait(20);
  return { id, handle: `@user${id}` };
}

async function loadPosts(id: number) {
  await wait(10);
  return ["Hello", "Week 2", "Trip photos"].map((title) => ({ author: id, title }));
}

async function loadDashboard(userId: number) {
  // TODO: load both in parallel
  return { profile: null, postCount: 0 };
}

console.log(await loadDashboard(5));

export {};
{ profile: null, postCount: 0 }
Show solution
ts
async function loadDashboard(userId: number) {
  const [profile, posts] = await Promise.all([loadProfile(userId), loadPosts(userId)]);
  return { profile, postCount: posts.length };
}

Test yourself

In function groupBy<T, K extends keyof T>(items: T[], key: K), what does K extends keyof T guarantee?

  1. K is a string
  2. key must be one of T's property names
  3. T has at least one key
  4. K is optional

Which type allows any subset of User's fields except id?

  1. Partial<User>
  2. Omit<Partial<User>, "name">
  3. Partial<Omit<User, "id">>
  4. Pick<User, "id">