Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 96 ยท Practice and Review

TypeScript Practice Exercises

30 graded TypeScript exercises with solutions: annotations, narrowing, type guards, classes, generics, utility, mapped, conditional and template literal types.

You learn TypeScript by writing types and watching the compiler react. Lessons build understanding, but only practice builds the instincts: reaching for a union instead of a string, narrowing before you use a value, letting a generic carry the type through, writing a mapped type instead of copying an interface. This page has 30 exercises that cover the whole course, grouped by topic and ordered from beginner to advanced inside each group.

There are two kinds of exercises. Runtime exercises ask you to write a function or class: the starter code runs as given, with stubs that return a placeholder, and comments show the output you should get. Type exercises ask you to write or fix a type. Their tests are compile-time checks that use the Expect and Equal helpers from the utility types lesson. Tests can't compile against a placeholder type, so they start inside a /* ... */ comment: write your type, delete the two comment lines, and run. If the program prints its success message, every test passed; if not, the error list tells you which test failed.

  • Try first, peek later. Give each exercise a real attempt before you open the solution.
  • Read the errors. A type error stops the run and shows main.ts(line,column): error TScode: message. The line and column point to the problem; the best practices lesson explains the common codes.
  • No any, no as. Unless the task says otherwise, solve each exercise without any and without type assertions. If you need one, the types are probably not yet right.
  • Compare, don't copy. Your solution can look different from ours and still be correct. Read ours for ideas.

Each group links to the lessons it practices. Keep the cheat sheet open in another tab, and look at the 40 classic programs for worked examples.

Types and functions

These practice your first types, typing functions, union types, literal types and arrays and tuples.

1. Format a price (Beginner)

Write formatPrice(amount, currency). The currency must be one of 'USD', 'EUR' or 'JPY', so give it a literal union type. Yen has no decimals; the others have two. Put the symbol in front: $, โ‚ฌ, ยฅ.

TypeScript Exercise 1: Format a price

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
type Currency = 'USD' | 'EUR' | 'JPY';

const SYMBOLS: Record<Currency, string> = { USD: '$', EUR: 'โ‚ฌ', JPY: 'ยฅ' };

function formatPrice(amount: number, currency: Currency): string {
  const decimals = currency === 'JPY' ? 0 : 2;
  return SYMBOLS[currency] + amount.toFixed(decimals);
}

Record<Currency, string> forces a symbol for every currency: add 'GBP' to the union and the object stops compiling until you add its symbol too.

2. Replace any with an interface (Beginner)

cartTotal accepts any, so the misspelled property in the last line slips through and the total is wrong. Write a CartItem interface (name: string, price: number, quantity: number), use it in the signature, and uncomment the last line: it must now be a compile error.

TypeScript Exercise 2: Replace any

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
interface CartItem {
  name: string;
  price: number;
  quantity: number;
}

function cartTotal(items: readonly CartItem[]): number {
  let total = 0;
  for (const item of items) {
    total += item.price * item.quantity;
  }
  return total;
}

With the interface, the object literal { name: 'Mug', price: 8, qty: 1 } fails the excess property check (TS2353: 'qty' does not exist in type 'CartItem'). readonly CartItem[] also tells callers the function won't change their array.

3. Optional and default parameters (Beginner)

Write buildUrl(path, query?, base = 'https://example.com'). query is an optional object whose values are strings or numbers; add it as a query string only when it has entries. Use URLSearchParams.

TypeScript Exercise 3: Build a URL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function buildUrl(
  path: string,
  query?: Record<string, string | number>,
  base = 'https://example.com',
): string {
  const entries = Object.entries(query ?? {}).map(([k, v]): [string, string] => [k, String(v)]);
  const search = entries.length > 0 ? '?' + new URLSearchParams(entries).toString() : '';
  return base + path + search;
}

base = '...' makes the parameter optional and infers string. URLSearchParams wants string values, so the numbers are converted first; it also encodes special characters for you.

4. Return a named tuple (Beginner)

Write minMax(values) that returns [min, max] as a named tuple [min: number, max: number], or undefined for an empty array. Accept a readonly number[].

TypeScript Exercise 4: Min and max

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function minMax(values: readonly number[]): MinMax | undefined {
  if (values.length === 0) return undefined;
  return [Math.min(...values), Math.max(...values)];
}

The tuple names show up in editor hints but don't change the type. Callers must check for undefined before destructuring, which is exactly the empty-array bug the return type prevents. For very large arrays, a loop avoids the argument limit of the spread.

5. An exhaustive switch (Easy)

Give nextLight a literal union type Light and implement it: red goes to green, green to yellow, yellow to red. Add a default branch that assigns the value to never, so adding 'flashing' to the union later becomes a compile error until it's handled.

TypeScript Exercise 5: Traffic light

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
type Light = 'red' | 'green' | 'yellow';

function nextLight(light: Light): Light {
  switch (light) {
    case 'red':
      return 'green';
    case 'green':
      return 'yellow';
    case 'yellow':
      return 'red';
    default: {
      const unhandled: never = light;
      throw new Error(`Unknown light: ${unhandled}`);
    }
  }
}

After the three cases, light is narrowed to never. A fourth union member would reach the default branch with a real type, and the assignment would fail with TS2322. See Discriminated Unions.

Narrowing

These practice narrowing, discriminated unions, custom type guards and any, unknown and never.

6. Describe any value (Easy)

Write describe(value) for string | number | boolean | null | string[] without any type assertions. Each branch must use the narrowed type: the string's length, the number with two decimals, the array's item count.

TypeScript Exercise 6: Describe a value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function describe(value: Value): string {
  if (value === null) return 'nothing';
  if (typeof value === 'string') return `string of length ${value.length}`;
  if (typeof value === 'number') return `number ${value.toFixed(2)}`;
  if (typeof value === 'boolean') return `boolean ${value}`;
  return `list of ${value.length} items`;
}

Check null first, because typeof null is 'object'. After the three typeof checks, only string[] is left, so the last line needs no check at all.

7. Payment fees with a discriminated union (Easy)

Model three payment methods as a discriminated union on method: card (with last4: string and international: boolean), paypal (with email: string) and bank (with iban: string). Implement fee(payment, amount): card 2.9% (plus 1% more if international), PayPal 3.4%, bank transfer a flat 0.50. Make the switch exhaustive.

TypeScript Exercise 7: Payment fees

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The starter's index signature [detail: string]: unknown accepts any extra property, so the code compiles but payment.international would be unknown. Your union replaces it with exact shapes.

Show solution
TypeScript
type Payment =
  | { method: 'card'; last4: string; international: boolean }
  | { method: 'paypal'; email: string }
  | { method: 'bank'; iban: string };

function fee(payment: Payment, amount: number): number {
  switch (payment.method) {
    case 'card':
      return amount * (payment.international ? 0.039 : 0.029);
    case 'paypal':
      return amount * 0.034;
    case 'bank':
      return 0.5;
    default: {
      const unhandled: never = payment;
      return unhandled;
    }
  }
}

Inside case 'card', payment is narrowed to the card member, so payment.international is available; in the other cases it isn't. That's the whole point of the tag.

8. A type guard for parsed JSON (Medium)

JSON.parse returns any. Write isUser(value: unknown): value is User that checks every property, including that roles is an array of strings. Use it to keep only the valid users.

TypeScript Exercise 8: isUser type guard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function isUser(value: unknown): value is User {
  return (
    typeof value === 'object' &&
    value !== null &&
    'id' in value &&
    typeof value.id === 'number' &&
    'name' in value &&
    typeof value.name === 'string' &&
    'roles' in value &&
    Array.isArray(value.roles) &&
    value.roles.every((role: unknown) => typeof role === 'string')
  );
}

Each 'key' in value check adds that property (as unknown) to the narrowed type, so the following typeof check is allowed without an assertion. Passing isUser to filter narrows the result to User[].

9. An assertion function (Medium)

Write assertDefined(value, name) as an assertion function: after the call, value must be narrowed to NonNullable<T>. If the value is null or undefined, throw an Error with the message <name> is required.

TypeScript Exercise 9: assertDefined

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function assertDefined<T>(value: T, name: string): asserts value is NonNullable<T> {
  if (value === null || value === undefined) {
    throw new Error(`${name} is required`);
  }
}

asserts value is NonNullable<T> tells the compiler that if the function returns at all, the value is defined. Hover over port after the call in your editor: its type changes from string | undefined to string.

10. Error messages from unknown (Easy)

In a catch block the error is unknown, because anything can be thrown. Write errorMessage(error: unknown): string: use the message of an Error, return a thrown string as is, use a message property of a plain object if it's a string, and fall back to String(error).

TypeScript Exercise 10: errorMessage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function errorMessage(error: unknown): string {
  if (error instanceof Error) return error.message;
  if (typeof error === 'string') return error;
  if (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string') {
    return error.message;
  }
  return String(error);
}

instanceof Error also matches subclasses such as RangeError. See Error Handling for why strict mode types catch variables as unknown.

Objects and classes

These practice object types, interfaces, classes, access modifiers, inheritance and abstract classes and readonly.

11. Immutable updates (Easy)

Book is fully readonly. Write applyDiscount(book, percent) that returns a new book with the reduced price (rounded to cents) and onSale: true, leaving the original untouched. Uncomment the last line to confirm that changing a property directly is an error.

TypeScript Exercise 11: Immutable updates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function applyDiscount(book: Book, percent: number): Book {
  const price = Math.round(book.price * (100 - percent)) / 100;
  return { ...book, price, onSale: true };
}

Spreading copies every property, and the later ones override. readonly is checked only by the compiler; use Object.freeze too if you need runtime protection.

12. A bank account class (Medium)

Write a BankAccount class with a constructor parameter property readonly owner: string, a JavaScript-private #balance, a balance getter, and deposit/withdraw methods that throw a RangeError for amounts that aren't positive or exceed the balance. Both methods return this so calls can be chained.

TypeScript Exercise 12: BankAccount

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
class BankAccount {
  #balance = 0;

  constructor(readonly owner: string) {}

  get balance(): number {
    return this.#balance;
  }

  deposit(amount: number): this {
    if (!(amount > 0)) throw new RangeError('Deposit must be positive');
    this.#balance += amount;
    return this;
  }

  withdraw(amount: number): this {
    if (!(amount > 0)) throw new RangeError('Withdrawal must be positive');
    if (amount > this.#balance) throw new RangeError(`Insufficient funds: balance is ${this.#balance}`);
    this.#balance -= amount;
    return this;
  }
}

!(amount > 0) also rejects NaN, which amount <= 0 would let through. With only a getter, account.balance = 1000 is a compile error (TS2540), and #balance can't be reached from outside even with tricks.

13. Abstract shapes (Medium)

Write an abstract class Shape with an abstract area(): number and a concrete describe(): string that returns "<name> with area <area to 2 decimals>". Then add Circle and Rectangle subclasses with override methods, and sort a list by area.

TypeScript Exercise 13: Abstract shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
abstract class Shape {
  abstract readonly name: string;
  abstract area(): number;
  describe(): string {
    return `${this.name} with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  readonly name = 'circle';
  constructor(readonly radius: number) {
    super();
  }
  override area(): number {
    return Math.PI * this.radius ** 2;
  }
}

class Rectangle extends Shape {
  readonly name = 'rectangle';
  constructor(readonly width: number, readonly height: number) {
    super();
  }
  override area(): number {
    return this.width * this.height;
  }
}

new Shape() is a compile error because the class is abstract, and a subclass that forgets area doesn't compile either. override is optional by default but required when noImplicitOverride is on.

14. Count with a Record (Easy)

Write countBy(items, keyOf) that returns a Record<string, number> of how many items produce each key. Then use it to count words by their first letter.

TypeScript Exercise 14: countBy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function countBy<T>(items: readonly T[], keyOf: (item: T) => string): Record<string, number> {
  const counts: Record<string, number> = {};
  for (const item of items) {
    const key = keyOf(item);
    counts[key] = (counts[key] ?? 0) + 1;
  }
  return counts;
}

counts[key] is typed number, but at runtime it's undefined the first time, so ?? 0 is necessary. With noUncheckedIndexedAccess the type would say number | undefined and force that check. See Index Signatures and Record.

Generics

These practice generics, constraints and defaults and generic interfaces and classes.

15. A generic last (Beginner)

Write last<T>(items) that returns the last element or undefined. The type of the result must follow the input: string | undefined for strings, User | undefined for users.

TypeScript Exercise 15: last

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function last<T>(items: readonly T[]): T | undefined {
  return items.at(-1);
}

T is inferred from the argument, so word is string | undefined and num is number | undefined. at(-1) already returns T | undefined, which is the honest type for an index that may not exist.

16. Pluck a property (Easy)

Write pluck(items, key) that returns an array of one property's values. The key must be a property of the item type, and the result type must be that property's type.

TypeScript Exercise 16: pluck

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}

K extends keyof T limits the key to 'name' | 'age' | 'active', and the indexed access type T[K] gives string for 'name' and number for 'age'. See keyof, typeof and Indexed Access Types.

17. Zip two arrays (Easy)

Write zip(a, b) that pairs elements by index into tuples and stops at the shorter array. The result type must be [A, B][].

TypeScript Exercise 17: zip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function zip<A, B>(a: readonly A[], b: readonly B[]): [A, B][] {
  const length = Math.min(a.length, b.length);
  return Array.from({ length }, (_, i): [A, B] => [a[i] as A, b[i] as B]);
}

Two type parameters let the arrays have different element types. The return annotation : [A, B] on the arrow function makes TypeScript build a tuple instead of the array (A | B)[]. The assertions are safe because i is below both lengths.

18. A generic cache (Medium)

Write a class Cache<K, V> with get(key), set(key, value) and getOrCompute(key, compute), which returns the cached value or calls compute(key) once and stores the result. Track hits and misses in a stats getter.

TypeScript Exercise 18: Generic cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
class Cache<K, V> {
  readonly #map = new Map<K, V>();
  #hits = 0;
  #misses = 0;

  get(key: K): V | undefined {
    return this.#map.get(key);
  }
  set(key: K, value: V): void {
    this.#map.set(key, value);
  }
  getOrCompute(key: K, compute: (key: K) => V): V {
    if (this.#map.has(key)) {
      this.#hits++;
      return this.#map.get(key) as V;
    }
    this.#misses++;
    const value = compute(key);
    this.#map.set(key, value);
    return value;
  }
  get stats(): { hits: number; misses: number } {
    return { hits: this.#hits, misses: this.#misses };
  }
}

Checking has instead of get(key) !== undefined keeps the cache correct when V itself includes undefined, which is also why the as V is justified.

19. Merge defaults (Medium)

Write withDefaults(defaults, overrides): overrides may contain any subset of the properties, the result has all of them with the default type. Ignore override values that are undefined. The function must be generic over any object type.

TypeScript Exercise 19: withDefaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function withDefaults<T extends object>(defaults: T, overrides: Partial<T>): T {
  const result = { ...defaults };
  for (const key of Object.keys(overrides) as (keyof T)[]) {
    const value = overrides[key];
    if (value !== undefined) result[key] = value;
  }
  return result;
}

Partial<T> makes every property optional, and the excess property check still catches retry. Object.keys returns string[] because objects can have extra keys at runtime, so the cast to (keyof T)[] is a known, deliberate exception. After the undefined check, value is T[keyof T] and the assignment type-checks.

Type manipulation

These practice keyof and typeof, utility types, mapped types, conditional types, template literal types and advanced type-level programming. From here on, most tests are compile-time checks: delete the /* and */ lines when your type is ready.

20. DTOs from one interface (Easy)

Using only built-in utility types, derive NewUser (everything except id and createdAt), UserPatch (every field of NewUser, all optional) and UserPreview (only id and name, both readonly).

TypeScript Exercise 20: Derive DTO types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
type NewUser = Omit<User, 'id' | 'createdAt'>;
type UserPatch = Partial<NewUser>;
type UserPreview = Readonly<Pick<User, 'id' | 'name'>>;

Deriving the types means a new field on User shows up in NewUser and UserPatch automatically. Utility types compose: Readonly<Pick<...>> first picks, then marks the result readonly.

21. Write Readonly and Partial yourself (Medium)

Write MyReadonly<T> and MyPartial<T> as mapped types, without using the built-in versions, and Mutable<T>, which removes readonly.

TypeScript Exercise 21: Your own mapped types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type MyPartial<T> = { [K in keyof T]?: T[K] };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };

A mapped type over keyof T is homomorphic: it keeps the original modifiers unless you change them, which is why MyPartial<Point> still has readonly y. -readonly removes the modifier, and -? would remove optionality (that's how Required works).

22. Element and promise types (Medium)

Write two conditional types with infer: ElementType<T> gives the element type of an array (readonly arrays too) and leaves other types unchanged; Unwrap<T> removes any number of nested Promise layers.

TypeScript Exercise 22: infer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
type ElementType<T> = T extends readonly (infer E)[] ? E : T;
type Unwrap<T> = T extends Promise<infer V> ? Unwrap<V> : T;

Matching against readonly (infer E)[] covers both mutable and readonly arrays, because string[] is assignable to readonly string[]. Unwrap calls itself until the type is no longer a promise; the built-in Awaited<T> does the same and also handles other "thenable" objects.

23. Event handler names (Medium)

Given an event map such as { click: { x: number; y: number }; keyPress: { key: string } }, write Handlers<Events> that produces { onClick: (event: { x: number; y: number }) => void; onKeyPress: ... }. Use key remapping with as and a template literal type.

TypeScript Exercise 23: Handler names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
type Handlers<Events> = {
  [K in keyof Events as `on${Capitalize<K & string>}`]: (event: Events[K]) => void;
};

K & string drops number and symbol keys, which Capitalize can't handle. Inside the object literal, each handler's e parameter is contextually typed from the mapped type, so e.x and e.key need no annotations.

24. Types from a const object (Easy)

Derive RouteName (the keys) and RoutePath (the values) from the ROUTES object instead of writing them by hand. Then make ROUTES keep its literal types with as const, and check it against Record<string, /${string}> with satisfies so a path without a leading slash is an error.

TypeScript Exercise 24: Types from values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
const ROUTES = {
  home: '/',
  profile: '/profile',
  settings: '/settings',
} as const satisfies Record<string, `/${string}`>;

type RouteName = keyof typeof ROUTES;
type RoutePath = (typeof ROUTES)[RouteName];

function navigate(name: RouteName): string {
  return `navigating to ${ROUTES[name]}`;
}

as const keeps the literal values, satisfies checks them without widening, and typeof turns the value into a type. With RouteName derived, the as keyof typeof ROUTES assertion in navigate is no longer needed. See keyof, typeof and Indexed Access Types.

25. Pick properties by value type (Hard)

Write PickByValue<T, V>, which keeps only the properties whose type is assignable to V, and FunctionKeys<T>, the union of keys whose values are functions.

TypeScript Exercise 25: PickByValue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
type PickByValue<T, V> = { [K in keyof T as T[K] extends V ? K : never]: T[K] };
type FunctionKeys<T> = { [K in keyof T]-?: T[K] extends (...args: never[]) => unknown ? K : never }[keyof T];

Remapping a key to never removes it. FunctionKeys uses a different trick: map each property to its own key or never, then index the result with [keyof T] to collect the union (the nevers disappear). -? stops optional properties from adding undefined to that union.

26. DeepPartial (Hard)

Write DeepPartial<T> that makes every property optional at every level, but leaves arrays' elements and functions alone (an array property becomes optional, but stays an array of the original element type).

TypeScript Exercise 26: DeepPartial

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
type DeepPartial<T> = T extends (...args: never[]) => unknown
  ? T
  : T extends readonly unknown[]
    ? T
    : T extends object
      ? { [K in keyof T]?: DeepPartial<T[K]> }
      : T;

Order matters: functions and arrays are objects too, so they must be handled before the general object case. Reading an optional property gives T | undefined, which is why the tests expect | undefined.

Async, errors and modern features

These practice promises and async/await, error handling, using declarations and generic types.

27. A typed timeout (Medium)

Write withTimeout(promise, ms) that resolves with the promise's value, or rejects with a TimeoutError (write the class) if it takes longer than ms. The return type must follow the input: Promise<string> in, Promise<string> out. Clear the timer either way.

TypeScript Exercise 27: withTimeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
class TimeoutError extends Error {
  override name = 'TimeoutError';
  constructor(readonly ms: number) {
    super(`Timed out after ${ms} ms`);
  }
}

function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
  let timer: ReturnType<typeof setTimeout> | undefined;
  const timeout = new Promise<never>((_, reject) => {
    timer = setTimeout(() => reject(new TimeoutError(ms)), ms);
  });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}

The timeout promise is Promise<never> because it never resolves, so Promise.race gives Promise<T | never>, which is just Promise<T>. ReturnType<typeof setTimeout> works in Node (a Timeout object) and browsers (a number).

28. tryCatch with a Result type (Medium)

Write tryCatch(fn) that runs fn and returns { ok: true, value } or { ok: false, error } with the error converted to an Error. Use it with JSON.parse and with a function that throws a non-Error value.

TypeScript Exercise 28: tryCatch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
function tryCatch<T>(fn: () => T): Result<T> {
  try {
    return { ok: true, value: fn() };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };
  }
}

The caller must check result.ok before touching value or error: the discriminated union makes forgetting the error case a compile error. The as { a: number } on JSON.parse is the honest place for an assertion; for untrusted input, validate with a type guard instead.

29. A disposable timer (Medium)

Write a class Timer that records the start time in its constructor and implements [Symbol.dispose](), printing <label> took <n> ms. Use it with a using declaration so the message appears when the block ends, even when the block throws.

TypeScript Exercise 29: Disposable timer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
class Timer implements Disposable {
  readonly #start = performance.now();
  constructor(readonly label: string) {}
  [Symbol.dispose](): void {
    console.log(`${this.label} took ${Math.round(performance.now() - this.#start)} ms`);
  }
}

function work(shouldFail: boolean): number {
  using timer = new Timer(shouldFail ? 'failing work' : 'work');
  let total = 0;
  for (let i = 0; i < 1_000; i++) total += i;
  if (shouldFail) throw new Error('boom');
  return total;
}

using calls [Symbol.dispose]() when the block exits by any route, like a finally you can't forget. The timer is printed before the caller's console.log, because disposal happens as work returns. Implementing the Disposable interface documents the intent and checks the method's signature.

30. A type-safe event emitter (Hard)

Write Emitter<Events>, where Events maps event names to payload types. on(name, listener) must type the listener's parameter from the map and return an unsubscribe function; emit(name, payload) must reject a wrong payload or an unknown event name.

TypeScript Exercise 30: Type-safe emitter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Show solution
TypeScript
type Listener<P> = (payload: P) => void;

class Emitter<Events> {
  readonly #listeners: { [K in keyof Events]?: Set<Listener<Events[K]>> } = {};

  on<K extends keyof Events>(name: K, listener: Listener<Events[K]>): () => void {
    const set = (this.#listeners[name] ??= new Set());
    set.add(listener);
    return () => {
      set.delete(listener);
    };
  }

  emit<K extends keyof Events>(name: K, payload: Events[K]): void {
    for (const listener of this.#listeners[name] ?? []) listener(payload);
  }
}

The generic K extends keyof Events ties the name to its payload: once name is 'checkout', the payload must be { total: number }. The mapped type for #listeners stores a correctly typed set per event, so no any is needed anywhere. The event system project extends this with once and tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In exercise 2, why does cartTotal([{ name: 'Mug', price: 8, qty: 1 }]) fail to compile once the parameter is readonly CartItem[]?

    Object literals passed directly to a typed parameter get an excess property check, and the required property quantity is missing too. With any[], neither problem was reported.
  2. 2. What does typeof value === 'object' tell you about value: string | null | string[]?

    typeof null is 'object' in JavaScript, and TypeScript models that: the narrowed type is string[] | null. That's why exercise 6 checks for null first.
  3. 3. In exercise 21, why does MyPartial<Point> keep readonly y?

    { [K in keyof T]?: T[K] } copies each property's readonly and optional modifiers and only adds ?. Use -readonly to remove readonly.
  4. 4. In exercise 30, what makes shop.emit('checkout', { total: '24' }) a compile error?

    The type parameter K is inferred from the first argument, and the second parameter's type Events[K] depends on it. A string total doesn't match number.

Summary

  • Types and functions: literal unions for fixed choices, interfaces instead of any, optional and default parameters, named tuples, and never in a default branch for exhaustive switches.
  • Narrowing: typeof, Array.isArray, === null, discriminated unions, type predicates for unknown data, assertion functions, and safe error messages from catch.
  • Objects and classes: immutable updates with spread, #private fields with getters, abstract classes with override, and Record counters with ?? 0.
  • Generics: inference from arguments, K extends keyof T with T[K], several type parameters, generic classes and Partial<T> for overrides.
  • Type manipulation: derive types with utility types, typeof and as const; write mapped types with modifiers and key remapping, conditional types with infer, and recursive types like DeepPartial.
  • Async, errors and modern features: generic promise wrappers, Result instead of exceptions, using with Symbol.dispose, and a fully typed event emitter with no any.

Next: TypeScript Interview Questions, to practice explaining these ideas out loud.