TypeScript 中的高阶函数在函数式编程中有广泛的应用。以下是一些主要的应用场景和示例:
- 函数组合
高阶函数可以用来组合多个函数,创建新的复杂函数:
type Compose = <T, U, V>(f: (y: U) => V, g: (x: T) => U) => (x: T) => V;
const compose: Compose = (f, g) => (x) => f(g(x));
const addOne = (x: number) => x + 1;
const double = (x: number) => x * 2;
const addOneThenDouble = compose(double, addOne);
console.log(addOneThenDouble(3)); // 输出: 8- 柯里化
高阶函数可以实现柯里化,将接受多个参数的函数转换为接受单一参数的函数序列:
type Curry = <T, U, V>(f: (x: T, y: U) => V) => (x: T) => (y: U) => V;
const curry: Curry = (f) => (x) => (y) => f(x, y);
const add = (x: number, y: number) => x + y;
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)); // 输出: 3- 函数装饰器
高阶函数可以用作函数装饰器,增强或修改现有函数的行为:
type Decorator = <T extends (...args: any[]) => any>(
fn: T
) => (...args: Parameters<T>) => ReturnType<T>;
const logDecorator: Decorator = (fn) => (...args) => {
console.log(`Calling function with arguments: ${args}`);
const result = fn(...args);
console.log(`Function returned: ${result}`);
return result;
};
const sum = (a: number, b: number) => a + b;
const loggedSum = logDecorator(sum);
console.log(loggedSum(2, 3));
// 输出:
// Calling function with arguments: 2,3
// Function returned: 5
// 5- 数组操作
高阶函数在数组操作中非常有用,如 map、filter 和 reduce:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((x) => x * 2);
console.log(doubled); // 输出: [2, 4, 6, 8, 10]
const evens = numbers.filter((x) => x % 2 === 0);
console.log(evens); // 输出: [2, 4]
const sum = numbers.reduce((acc, cur) => acc + cur, 0);
console.log(sum); // 输出: 15- 惰性求值
高阶函数可以用于实现惰性求值,延迟计算直到需要结果:
type LazyValue<T> = () => T;
const lazyMap = <T, U>(arr: T[], fn: (x: T) => U): LazyValue<U[]> => {
return () => arr.map(fn);
};
const lazyNumbers = lazyMap([1, 2, 3], (x) => x * 2);
console.log("Lazy evaluation:", lazyNumbers()); // 输出: Lazy evaluation: [2, 4, 6]这些示例展示了 TypeScript 中高阶函数在函数式编程中的多种应用。高阶函数使代码更加简洁、可读和可维护,同时提高了代码的灵活性和可复用性[2]。通过使用高阶函数,我们可以更好地抽象出公共逻辑和模式,实现函数式编程的核心概念,如纯函数、不可变性和函数组合。
Citations: [1] https://cloud.tencent.cn/developer/information/Typescript%20-%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0%E7%9A%84%E7%B1%BB%E5%9E%8B%E5%AE%9A%E4%B9%89-video [2] https://puhuiju.com/9295.html [3] https://paro.one/20190908-higher-kinded-types-in-typescript/ [4] https://blog.csdn.net/qq_43644292/article/details/137234145 [5] https://juejin.cn/post/6844903879822278664