【发布时间】:2021-08-26 09:29:12
【问题描述】:
考虑任意数量的函数,每个函数都接受一个参数并返回一个值(不要担心它们的作用,而不是重点):
function toNumber(input: string): number {
return parseInt(input)
}
function toBoolean(input: number): boolean {
return input > 0
}
function toString(input: boolean): string {
return input.toString()
}
这些函数可以像这样链接起来(在 fp 中可能有更好的术语),因为每个函数都将前一个的返回类型作为参数:
type Fn<I, O> = (input: I) => O
function chain(...fns: Fn<any, any>[]): Fn<any, any> {
return (input: any) => {
let result = input
for (const fn of fns) {
result = fn(result)
}
return result
}
}
const chained = chain(toNumber, toBoolean, toString)
const result = chained('5') // returns "true"
打字稿中有没有办法使chain 函数类型安全?由于我们有任意数量的函数,因此必须有任意数量的泛型参数。
我可以做这样的事情(固定数量的重载):
declare function chain<S, T1>(fn: Fn<S, T1>): Fn<S, T1>
declare function chain<S, T1, T2>(fn1: Fn<S, T1>, fn2: Fn<T1, T2>): Fn<S, T2>
declare function chain<S, T1, T2, T3>(fn1: Fn<S, T1>, fn2: Fn<T1, T2>, fn3: Fn<T2, T3>): Fn<S, T3>
但是有更好的方法吗?
【问题讨论】:
标签: typescript generics typescript-typings typescript-generics