TypeScript · Lesson 8

Functional Patterns (bridge to F#)

Option, Result, pipe, immutable updates and typed events in TypeScript, each shown next to its F# equivalent.

5 min read

In short

  • Option makes absence explicit: F# Some and None
  • Result puts errors in the signature: andThen is Result.bind
  • pipe reads left to right, like F#'s |>
  • Spread updates share untouched structure
  • These are the ideas you'll use daily in F#

F# is a functional-first language. Its everyday tools are discriminated unions, Option, Result, the pipe operator |> and immutable data. You can write all of them in TypeScript, and doing that first makes F# feel familiar instead of foreign. This topic builds each one in TypeScript and shows the F# version next to it.

Discriminated unions: the foundation

A union of object types that share a literal "tag" field. Checking the tag narrows the type.

▶ Try
type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'rect'; width: number; height: number };

function area(s: Shape): number {
  switch (s.kind) {
    case 'circle': return Math.PI * s.radius ** 2;
    case 'rect':   return s.width * s.height;
    default: {
      const unreachable: never = s;   // compile error if a case is missing
      return unreachable;
    }
  }
}
▶ Try
type Shape =
    | Circle of radius: float
    | Rect of width: float * height: float

let area shape =
    match shape with
    | Circle r -> System.Math.PI * r * r
    | Rect (w, h) -> w * h          // missing cases are a compiler warning

In F#, unions are built into the language, and match is the switch with exhaustiveness checking.

Option: "maybe there's a value"

Instead of null/undefined leaking everywhere, make absence explicit and give it a small API.

▶ Try
type Option<T> = { readonly kind: 'some'; readonly value: T } | { readonly kind: 'none' };

const map = <T, U>(o: Option<T>, f: (v: T) => U): Option<U> =>
  o.kind === 'some' ? { kind: 'some', value: f(o.value) } : o;
▶ Try
let tryParseInt (s: string) =
    match System.Int32.TryParse s with
    | true, n -> Some n
    | _ -> None

tryParseInt "42" |> Option.map (fun n -> n * 2) |> Option.defaultValue 0   // 84
IdeaTypeScript (this topic)F#
wrap a valuesome(x)Some x
nothingnoneNone
transformmap(o, f)Option.map f o
chain an optional stepflatMap(o, f)Option.bind f o
fallbackgetOrElse(o, d)Option.defaultValue d o

Result: errors as values

Exceptions are invisible in signatures. Result<T, E> puts the failure type in the signature, and andThen (F#'s Result.bind) chains steps that can fail. The first error short-circuits the rest. This is railway-oriented programming, a term coined by Scott Wlaschin in the F# community.

▶ Try
type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E };

const parsed = andThen(parseAge(input), (age) => (age >= 18 ? ok(age) : err('too young')));
▶ Try
let validateAge age = if age >= 18 then Ok age else Error "too young"

parseAge input |> Result.bind validateAge |> Result.map (fun a -> a + 1)

TypeScript bonus: andThen can widen the error type (E1 | E2), while F# requires both steps to share one error type (you usually wrap them in an error union).

Pipe: read left to right

h(g(f(x))) reads inside-out. F# writes it as a pipeline:

▶ Try
[1; 2; 3; 4]
|> List.filter (fun n -> n % 2 = 0)
|> List.map (fun n -> n * 10)
|> List.sum                         // 60

TypeScript has no |> operator (yet), but a pipe(value, f, g, h) function with overloads gives the same readability and full type inference at each step:

▶ Try
const total = pipe(
  [1, 2, 3, 4],
  (xs) => xs.filter((n) => n % 2 === 0),
  (xs) => xs.map((n) => n * 10),
  (xs) => xs.reduce((a, b) => a + b, 0),
); // number

Immutability and structural sharing

F# records and lists are immutable by default, and "updating" creates a new value:

▶ Try
type User = { Name: string; Age: int }
let older = { user with Age = user.Age + 1 }   // copy-and-update; `user` is unchanged

In TypeScript you opt in with readonly, Readonly<T>, ReadonlyArray<T>, as const, a DeepReadonly<T> type, and spread-based updates:

▶ Try
const older = { ...user, age: user.age + 1 };

Structural sharing means an update copies only the path from the root to the change, and every untouched branch is the same object. That keeps updates cheap and makes change detection an O(1) reference check (prev.todos === next.todos), which is exactly what React, Redux and Angular's OnPush rely on.

Type-safe events

Mapping event names to payload tuples ({ login: [user: string]; logout: [] }) lets the compiler check emit('login', 'ann') and the listener's parameters. It's the TypeScript equivalent of F#'s typed Event<'T> / IObservable<'T>.

Gotchas

  • Readonly<T> is shallow: nested objects stay mutable. You need a recursive DeepReadonly.
  • readonly is compile-time only. Use Object.freeze for runtime protection (also shallow).
  • Interfaces don't satisfy Record<string, X> constraints (no implicit index signature). Use type aliases for event maps.
  • Overloaded pipe functions have a maximum arity. Beyond it, inference stops (libraries ship 10–20 overloads).
  • Don't mix styles halfway: a Result-returning function that also throws is the worst of both.

In interviews / in real codebases

Side note
  • fp-ts, Effect, neverthrow and ts-results bring Option/Result/pipe to TypeScript. Many teams use a tiny hand-rolled Result for domain validation and keep exceptions for truly exceptional failures.
  • Redux/NgRx reducers, React state updates and immutable caches all depend on structural sharing.
  • When you move to F#, expect Option, Result, |>, match and immutable records from day one. These exercises are those same ideas with TypeScript syntax.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app