微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);

原文地址:https://www.jb51.cc/js/158925.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐