TypeScript
Beginner
1 min read
Higher-Order Functions and this Typing
Example
// Higher-order function — map with generics
function mapArray<T, U>(arr: T[], fn: (item: T, index: number) => U): U[] {
return arr.map(fn);
}
const doubled = mapArray([1, 2, 3], x => x * 2); // number[]
const lengths = mapArray(["hi", "hello"], s => s.length); // number[]
// Currying
function curry<A, B, C>(fn: (a: A, b: B) => C): (a: A) => (b: B) => C {
return (a) => (b) => fn(a, b);
}
const curriedAdd = curry((a: number, b: number) => a + b);
const add5 = curriedAdd(5);
console.log(add5(3)); // 8
// 'this' parameter typing
interface Counter {
count: number;
increment(this: Counter): void;
reset(this: Counter): void;
}
const counter: Counter = {
count: 0,
increment() { this.count++; },
reset() { this.count = 0; },
};
// Memoisation wrapper preserving function signature
function memoize<Args extends unknown[], R>(
fn: (...args: Args) => R
): (...args: Args) => R {
const cache = new Map<string, R>();
return (...args) => {
const key = JSON.stringify(args);
if (!cache.has(key)) cache.set(key, fn(...args));
return cache.get(key)!;
};
}
const expensiveSqrt = memoize((n: number) => Math.sqrt(n));
console.log(expensiveSqrt(144)); // 12
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript