Functional Programming in TypeScript: Advanced Level
\n\nFunctional programming (FP) is a paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. TypeScript, as a superset of JavaScript, provides a powerful type system that allows implementing many FP concepts at a new level of safety and expressiveness. In this article, we will explore advanced techniques: from strict immutability to working with monads and functors.
\n\nImmutability and Working with Immutable Structures
\n\nImmutability is a cornerstone of FP. In TypeScript, we can guarantee it at the type level using the readonly modifier and utility types.
// Deep immutability via ReadonlyDeep\ntype DeepReadonly<T> = {\n readonly [P in keyof T]: DeepReadonly<T[P]>;\n};\n\ninterface User {\n name: string;\n address: { city: string; zip: number };\n}\n\nconst user: DeepReadonly<User> = {\n name: "Alice",\n address: { city: "Moscow", zip: 101000 }\n};\n\n// user.address.city = "SPb"; // Error! Property is read-only\n\nFor safe data updates, use pure functions that return new objects:
\n\nfunction updateZip(user: DeepReadonly<User>, newZip: number): DeepReadonly<User> {\n return { ...user, address: { ...user.address, zip: newZip } };\n}\n\nconst updatedUser = updateZip(user, 190000);\n\nFunction Composition and Currying
\n\nComposition allows building complex transformations from simple functions. In TypeScript, using generics, we can create type-safe combinators.
\n\n// Type for composing two functions\ntype Compose<A, B, C> = (f: (b: B) => C, g: (a: A) => B) => (a: A) => C;\n\nconst compose: Compose<any, any, any> = (f, g) => (x) => f(g(x));\n\n// Example: converting a string to a number and incrementing by 1\nconst toNumber = (s: string): number => parseInt(s, 10);\nconst increment = (n: number): number => n + 1;\n\nconst parseAndIncrement = compose(increment, toNumber);\nconsole.log(parseAndIncrement("5")); // 6\n\nCurrying transforms a function of multiple arguments into a sequence of functions of one argument. This makes composition more flexible:
\n\n// Universal currying function with types\nfunction curry<T1, T2, R>(fn: (a: T1, b: T2) => R): (a: T1) => (b: T2) => R {\n return (a: T1) => (b: T2) => fn(a, b);\n}\n\nconst add = (a: number, b: number): number => a + b;\nconst curriedAdd = curry(add);\nconst add5 = curriedAdd(5);\nconsole.log(add5(3)); // 8\n\nFunctors and Monads: Working with Contexts
\n\nFunctor is a data structure that supports the map operation. In TypeScript, a functor can be an array, a Promise, or a custom type.
// Option (Maybe) functor for safe null/undefined handling\ninterface Option<T> {\n map<U>(fn: (value: T) => U): Option<U>;\n getOrElse(defaultValue: T): T;\n}\n\nclass Some<T> implements Option<T> {\n constructor(private value: T) {}\n map<U>(fn: (value: T) => U): Option<U> {\n return new Some(fn(this.value));\n }\n getOrElse(_: T): T {\n return this.value;\n }\n}\n\nclass None<T> implements Option<T> {\n map<U>(_: (value: T) => U): Option<U> {\n return new None<U>();\n }\n getOrElse(defaultValue: T): T {\n return defaultValue;\n }\n}\n\n// Usage\nconst maybeNumber: Option<number> = new Some(42);\nconst result = maybeNumber.map(x => x * 2).getOrElse(0); // 84\n\nMonad extends a functor with the flatMap (or bind