javascript – 键入系统的功能组合

我如何为撰写添加类型?
问题基本上归结为为此编写类型:
const compose = (...funcs) => x => funcs.reduce((acc,func) => func(acc),x);

并使用它:

compose(x => x + 1,x => x * 2)(3);

在此示例中,compose的类型被推断为:

const compose: (...funcs: any[]) => (x: any) => any

这只是一堆……

有没有一种很好的方法添加类型来组成?

解决方法

虽然不可能输入这样的函数来接受任意数量函数,但我们可以编写一个具有最多给定数量函数的重载的compose版本.对于大多数实际应用,它应该足以允许最多5个功能的组合,并且我们总是可以在需要时添加更多的重载.

我还添加一个重载,当类型没有不同时,我们只有一个类型在整个compose中处理.如果参数类型和返回类型相同,这允许传入任意数量函数.

function compose<A,B,C,D,E,F>(fn: (p: A) => B,fn2: (p: B) => C,fn3: (p: C) => D,fn4: (p: D) => E,fn5: (p: E) => F): (p: A) => F
function compose<A,E>(fn: (p: A) => B,fn4: (p: D) => E): (p: A) => E
function compose<A,D>(fn: (p: A) => B,fn3: (p: C) => D): (p: A) => D
function compose<A,C>(fn: (p: A) => B,fn2: (p: B) => C): (p: A) => C
function compose<T>(...funcs: Array<(p: T) => T>) : (p: T) => T // Special case of parameter and return having the same type
function compose(...funcs: Array<(p: any) => any>) {
    return (x: any) => funcs.reduce((acc,x)
};

// Usage
// First argument type must be specified,rest are inferred correctly
let fn = compose((x : number) => x + 1,x => x * 2); // fn will be (p: number) => number
let d = fn(3); // d will be number 

let fn2 = compose((x : number) => x + 1,x => x * 2,x=> x.toString(),x => x.toLowerCase()); // fn will be (p: number) => string and we get intelisense and type safety in each function 

// Any number of functions but a single type
let fnMany = compose((x : number) => x + 1,x => x * 2);

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...