javascript – 键入系统的功能组合

前端之家收集整理的这篇文章主要介绍了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.f2er.com/js/158925.html

猜你在找的JavaScript相关文章