gpt4 book ai didi

javascript - 函数组合的类型系统

转载 作者:数据小太阳 更新时间:2023-10-29 04:41:34 24 4
gpt4 key购买 nike

如何为 compose 添加类型?
问题基本上归结为为此编写类型:

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

这只是一堆 any...

compose有没有什么好的方法可以添加类型?

最佳答案

虽然不可能键入这样一个函数来接受任意数量的函数,但我们可以编写一个版本的 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, B, C, D, E>(fn: (p: A) => B, fn2: (p: B) => C, fn3: (p: C) => D, fn4: (p: D) => E): (p: A) => E
function compose<A, B, C, D>(fn: (p: A) => B, fn2: (p: B) => C, fn3: (p: C) => D): (p: A) => D
function compose<A, B, 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, func) => func(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, x => x * 2, x => x * 2, x => x * 2, x => x * 2, x => x * 2);

关于javascript - 函数组合的类型系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49528282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com