Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 96 ยท Practice and Review

TypeScript Programs: 40 Classic Examples

40 classic TypeScript programs with output: primes, Fibonacci, palindromes, Roman numerals, sorting, stacks, trees, LRU caches and typed utilities.

Some programs are classics because every developer writes them sooner or later: check whether a number is prime, reverse the words of a sentence, sort a list, search it, build a stack, count words, find the shortest path through a small graph. They fit on one screen, yet each one trains a real skill. In TypeScript they train a second skill on top: choosing types that describe the data precisely, so the compiler catches the mistakes before the program runs.

This page collects 40 of them, all written from scratch in strict, modern TypeScript. Every program is complete. Press Run and our server type-checks it with the TypeScript 7 compiler and then runs it with Node.js; the output appears below the editor. Change the code, break a type on purpose, and run again: a type error stops the run and shows only the error list, so you see exactly what the compiler sees. Programs that read input come with values in the Input box, which you can edit.

A few habits run through every example. Functions annotate their parameters and return types; local variables are inferred. Data comes in readonly arrays when a function doesn't need to change it. Generic functions work for any element type, and unions of literals replace magic strings. Where JavaScript has a built-in that solves the problem, the program shows it next to the hand-written version, because in real code you should use the built-in. If you'd rather write these yourself first, try the practice exercises, and keep the cheat sheet open for syntax.

Numbers and math

These practice primitive types, typing functions and type inference.

1. FizzBuzz with a union return type

The return type number | 'Fizz' | 'Buzz' | 'FizzBuzz' documents every possible result. A typo such as 'Fizzbuzz' would be a compile error, not a silent bug.

TypeScript 1. FizzBuzz

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.

2. Prime numbers with a sieve

The sieve of Eratosthenes crosses out multiples instead of testing each number. A Uint8Array is a compact array of flags; the outer loop stops at the square root because every composite number has a factor at most that large.

TypeScript 2. Sieve of Eratosthenes

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.

3. Factorial with bigint

number loses exact digits above Number.MAX_SAFE_INTEGER (about 9 ร— 10^15), so 25! comes out rounded. bigint is exact at any size, but TypeScript won't let you mix the two in arithmetic: 1n * 2 is a compile error, so the loop converts with BigInt(i).

TypeScript 3. Factorial with bigint

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.

4. Fibonacci with a generator

A generator produces values on demand. Its type Generator<number> says it yields numbers; the caller takes as many as it needs. Lesson: Iterators and Generators.

TypeScript 4. Fibonacci generator

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.

5. GCD and LCM

Euclid's algorithm replaces the pair (a, b) with (b, a % b) until b is 0. The least common multiple follows from a * b / gcd; dividing first keeps the intermediate value small.

TypeScript 5. GCD and LCM

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.

6. Armstrong numbers

An Armstrong number equals the sum of its digits, each raised to the number of digits: 153 = 1ยณ + 5ยณ + 3ยณ. Turning the number into a string is the simplest way to get its digits.

TypeScript 6. Armstrong numbers

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.

7. Number bases

toString(radix) and parseInt(text, radix) convert between bases 2 to 36. The hand-written version shows the algorithm: repeated division, collecting remainders. A literal union restricts the bases the function accepts.

TypeScript 7. Number bases

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.

Notice that DIGITS[rest % base] has type string here. Under noUncheckedIndexedAccess (not part of strict) it would be string | undefined, and you'd need to handle the missing case. See Index Signatures and Record.

8. Temperature conversion

A literal union for the unit and a Record of converters keyed by from-to strings. A template literal type builds every pair, so a missing conversion is a compile error.

TypeScript 8. Temperature conversion

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 as [Unit, Unit] assertion is safe only because a Conversion string always has that shape. Assertions turn checking off, so keep them this narrow. See Type Assertions.

Strings

These practice string methods with types: union types, Record and Maps.

9. Palindromes

Normalize first: lowercase, then keep only letters and digits with a Unicode-aware regular expression (\p{L} is any letter, \p{N} any digit, the u flag enables them). Array.from splits by code points, so emoji and accented letters survive the reversal.

TypeScript 9. Palindromes

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.

10. Reverse the words of a sentence

Split on runs of whitespace, reverse, join. filter(Boolean) would also work to drop empty strings, but trimming first means there are none.

TypeScript 10. Reverse words

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.

11. Anagrams

Two words are anagrams when their sorted letters match. A Map<string, string[]> keyed by that sorted "signature" groups a whole list of words in one pass.

TypeScript 11. Anagram groups

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.

groups.get(key) returns string[] | undefined, so the code must check before calling push. That check is exactly the bug TypeScript prevents.

12. Count vowels and consonants

A Record<'vowels' | 'consonants' | 'other', number> requires all three counters: forget one in the initial object and the compiler complains.

TypeScript 12. Vowels and consonants

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.

13. Word frequency

Count with a Map, then sort the entries by count (descending) and by word for ties. The tuple type [string, number] comes straight from Map.entries().

TypeScript 13. Word frequency

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.

match returns RegExpMatchArray | null; ?? [] turns "no match" into an empty array so the rest of the code needs no null checks.

14. Title case

Capitalize each word but keep short "minor" words lowercase unless they come first. A ReadonlySet makes the lookup fast and stops anyone from adding to it by accident.

TypeScript 14. Title case

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.

15. Caesar cipher

Shift each letter by a fixed amount, wrapping around the alphabet. The ((x % n) + n) % n trick keeps the result positive for negative shifts, which is how decoding works.

TypeScript 15. Caesar cipher

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.

16. Roman numerals both ways

A readonly table of [value, symbol] tuples, largest first, converts numbers greedily. Parsing goes the other way: a symbol smaller than the one after it is subtracted (the I in IV).

TypeScript 16. Roman numerals

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.

Arrays and algorithms

These practice generics, generic constraints and function types. Each algorithm is written once and works for any element type.

Binary search halves the range on every step, so a million sorted items need at most 20 comparisons. The comparator parameter makes it generic: numbers, strings or objects all work.

TypeScript 17. Binary search

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.

sorted[mid] as T is there for projects that turn on noUncheckedIndexedAccess, where indexing gives T | undefined. The loop bounds guarantee mid is valid, so the assertion is justified. >>> 1 is a fast integer halving.

18. Insertion sort with a comparator

Insertion sort is simple and fast for small or nearly sorted arrays. This version copies the input, so the caller's array is never changed, which the readonly parameter promises.

TypeScript 18. Insertion sort

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.

19. Merge sort

Divide the array in half, sort each half recursively, then merge the two sorted halves. It always takes O(n log n) time and is stable: equal items keep their order.

TypeScript 19. Merge sort

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.

In real code, use toSorted (ES2023, non-mutating) or sort: both are stable in every modern engine.

20. Quicksort

Pick a pivot, partition the rest into smaller and larger items, and sort each part. This short, readable version builds new arrays; production versions partition in place.

TypeScript 20. Quicksort

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 length check proves the array has at least one element, but TypeScript can't connect a length test to destructuring, so the assertion as [number, ...number[]] (a tuple with a first element) tells it so.

21. Chunk an array

Split a list into groups of a fixed size. The return type T[][] keeps the element type: chunking strings gives string[][].

TypeScript 21. Chunk

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.

22. Remove duplicates by key

new Set(array) removes duplicate primitives. For objects you need a key: the K extends keyof T constraint lets the caller name any property, and a typo in the property name is a compile error.

TypeScript 22. Unique by key

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.

23. Group by

Object.groupBy and Map.groupBy (ES2024) group items by a key function. The typed hand-written version shows what they do. Partial<Record<...>> is the honest type for the result, because a group with no items is missing.

TypeScript 23. Group by

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.

??= assigns only when the left side is null or undefined, so each group's array is created on first use.

24. Matrix multiplication

A Matrix type alias makes signatures readable. The function checks the dimensions at runtime, because array lengths aren't part of the number[][] type.

TypeScript 24. Matrix multiplication

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.

Data structures

These practice classes, access modifiers and generic classes. Each structure keeps its storage in a #private field, so outside code can only use the public methods.

25. Stack: balanced brackets

A stack is last in, first out. Checking brackets is its classic use: push every opener, and every closer must match the opener on top.

TypeScript 25. Stack and balanced brackets

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.

26. Queue with two stacks

A queue is first in, first out. Array.prototype.shift is O(n) because it moves every element, so this queue uses two arrays: new items go into inbox, and outbox is refilled (reversed) only when it runs empty. Each item moves once, so operations are O(1) on average.

TypeScript 26. Queue

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.

Returning this from enqueue allows chaining, and the type this stays correct even in subclasses.

27. Linked list you can loop over

A singly linked list of nodes. Implementing [Symbol.iterator] as a generator makes the list work with for...of, spread and Array.from, because it now matches the Iterable<T> interface.

TypeScript 27. Iterable linked list

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.

28. Binary search tree

Each node keeps smaller values on the left and larger on the right, so an in-order traversal yields the values sorted. The T type needs an ordering, so the tree takes a comparator in its constructor through a parameter property.

TypeScript 28. Binary search tree

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 type of side is 'left' | 'right', so current[side] is checked: TypeScript knows both properties are TreeNode<T> | undefined. The recursive helpers take the node explicitly. A shortcut such as *inOrder(node = this.#root) type-checks but recurses forever, because passing an undefined child triggers the default and starts again at the root.

29. LRU cache

A least-recently-used cache drops the entry that hasn't been used for the longest time. A Map remembers insertion order, so deleting and re-inserting a key on every access moves it to the end, and the first key is always the oldest.

TypeScript 29. LRU 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.

has + get with as V instead of only get matters when V itself can be undefined: a stored undefined must still count as a hit.

30. Priority queue with a binary heap

A min-heap stores the smallest item at the root of a tree packed into an array (the children of index i are 2i + 1 and 2i + 2). Both push and pop take O(log n). The priority comes from a function, so any item type works.

TypeScript 30. Priority queue

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.

An unweighted graph as a ReadonlyMap<string, readonly string[]> of neighbors. Breadth-first search visits nodes in order of distance, so the first time it reaches the target it has found a shortest path. A second map records where each node was reached from, to rebuild the path.

TypeScript 31. Breadth-first search

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 queue is an array with a moving read index i instead of shift(), which keeps the search linear.

Typed utilities

These practice utility types, mapped types, conditional types and overloads. The interesting part of each program is its signature.

32. Memoize any function

memoize accepts a function with any parameter list and returns a function of the same type. Parameters<F> and ReturnType<F> keep the signature, so callers get full checking on the cached version.

TypeScript 32. Memoize

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.

JSON.stringify makes a simple cache key for arguments that are plain data. Functions or class instances need a different key strategy, such as a WeakMap.

33. A typed pipe

pipe passes a value through a list of functions. Overloads give each step's input the previous step's output type, so a step that expects the wrong type is a compile error.

TypeScript 33. Typed pipe

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.

wordCount has type number, inferred through all three steps. Swap words and count and the call no longer type-checks: the run stops with error TS2345, because no overload lets a string flow into a step that expects an array.

34. Safe JSON parsing with a Result type

JSON.parse returns any, which silently switches checking off. This version returns unknown inside a Result discriminated union, and a type guard checks the shape before the data is used.

TypeScript 34. Safe JSON parsing

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.

'name' in value narrows value to an object with a name property of type unknown, which the typeof check then narrows to string. That's why no assertion is needed.

35. Typed property paths

A recursive template literal type lists every dot-separated path through an object type, and PathValue computes the type at that path. get(settings, 'theme.fontSize') returns a number; a misspelled path doesn't compile.

TypeScript 35. Typed property paths

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 implementation has to use assertions, because the compiler can't follow a runtime loop through a type-level recursion. The signature is what protects every caller. Lesson: Advanced Type-Level Programming.

36. Deep freeze with a DeepReadonly type

Object.freeze is shallow at runtime and Readonly<T> is shallow in the types. A recursive mapped type and a recursive function make both deep.

TypeScript 36. Deep freeze

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.

Each @ts-expect-error line compiles only because it is a type error, which proves the type is deep. The program then runs those lines anyway, and the deep freeze stops them at runtime too: ES modules run in strict mode, where writing to a frozen object throws a TypeError instead of failing silently.

Programs that read input

These practice reading standard input with types, as in TypeScript with Node.js. Each one reads the Input box with readFileSync(0, 'utf8').

37. Statistics from input

Parse every number, skip invalid tokens, and print count, mean, median, standard deviation and range. A returned object type documents every statistic in one place.

TypeScript 37. Statistics

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 ! non-null assertions say "this index exists", which the count checks guarantee. Use them only when you can point to the reason, as here.

38. CSV to typed records

Read CSV lines, map each row to an Employee with typed fields, and report invalid rows instead of crashing. Then group salaries by department with Map.groupBy.

TypeScript 38. CSV to typed records

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.

flatMap with [r.employee] or [] keeps only the good rows and narrows the type to Employee[] in one step. (A filter((r) => r.ok) would also narrow here, thanks to inferred type predicates from TypeScript 5.5.)

39. Bank account commands

Each input line is a command. A discriminated union models the parsed commands, and switch handles each kind; the never check guarantees every command is handled.

TypeScript 39. Bank account commands

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.

Inside if (name === 'balance' || name === 'history'), name is narrowed to 'balance' | 'history', so { kind: name } is a valid Command without any assertion.

40. Expression calculator

A tokenizer turns text into typed tokens, and a recursive-descent parser evaluates + - * /, parentheses and unary minus with the right precedence. It's the biggest program here and a good model for any small language.

TypeScript 40. Expression calculator

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 y (sticky) flag makes the regular expression match exactly at lastIndex, so the tokenizer can't skip over garbage. token?.value === '-' works on both token kinds, because both have a value property; TypeScript allows comparing number | string with '-'.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In program 3, why does factorial multiply by BigInt(i) instead of i?

    bigint and number are separate types and JavaScript throws a TypeError when you mix them. TypeScript catches it at compile time with error TS2365.
  2. 2. In program 11, why must the code check group before calling group.push(word)?

    A Map can't promise a key exists, so get includes undefined in its return type. strictNullChecks forces you to handle that case.
  3. 3. What does uniqueBy(contacts, 'emial') do in program 22?

    The constraint K extends keyof T limits the key argument to 'id' | 'email' | 'name', so a typo is a compile error before the program runs.
  4. 4. In program 33, what is the type of wordCount?

    The three-step overload chains the types: string to string (trim), string to string[] (words), readonly unknown[] to number (count). The last step's return type is the result.

Summary

  • Number programs use %, Math.floor, generators and bigint for exact large values; TypeScript keeps bigint and number apart.
  • String programs normalize Unicode with \p{L} and the u flag, split by code points with Array.from, and count with Map or a Record whose keys come from a literal union.
  • Algorithms are written once as generics with a comparator, so they work for numbers, strings and objects; readonly parameters promise not to change the caller's data.
  • Data structures hide their storage in #private fields, return T | undefined honestly from pop, get and peek, and implement Iterable<T> to work with for...of and spread.
  • Typed utilities show the real power of TypeScript: memoize, pipe, Result, typed property paths and DeepReadonly put the safety in the signature.
  • Input programs parse untrusted text into discriminated unions, report bad rows instead of crashing, and use a never check so every case is handled.

Next: TypeScript Practice Exercises, where you write programs like these yourself and compare with our solutions.