juxt 调用函数数组来返回值数组。文件:ramda https://ramdajs.com/docs/#juxt clojure https://clojuredocs.org/clojure.core/juxt
我正在尝试输入一个不带覆盖的数据优先版本,但我不知道如何将函数元组映射到它们的返回值 https://github.com/microsoft/TypeScript/pull/26063。这就是我所拥有的:
type JuxtFn<T> = (x: T) => any
function juxt<T, Fs extends JuxtFn<T>[]>(
x: T,
fns: Fs,
): {[K in keyof Fs]: ReturnType<Fs[K]>} {
return fns.map(fn => fn(x))
}
它抱怨(以及其他抱怨)
Type 'Fs[K]' does not satisfy the constraint '(...args: any) => any'.
这在 TypeScript 中可能吗?
对于这种情况,请考虑使用函数重载:
type JuxtFn<T> = (x: T) => any
function juxt<T, Fn extends JuxtFn<T>, Fns extends Fn[]>(
x: T,
fns: [...Fns],
): { [K in keyof Fns]: Fns[K] extends Fn ? ReturnType<Fns[K]> : never }
function juxt<T, Fs extends JuxtFn<T>[]>(
x: T,
fns: Fs,
) {
return fns.map(fn => fn(x))
}
// [string[], Promise<number>]
const result = juxt(
10,
[(v: number) => ['s'], (v: number) => Promise.resolve(42)]
)
操场 https://tsplay.dev/wj4L8m
我添加了条件类型Fns[K] extends Fn ? ReturnType<Fns[K]> : never
只是为了向 TypeScript 保证Fns[K]
是一个函数
您可以找到有关推断返回类型的更多信息[].map
here https://stackoverflow.com/questions/57913193/how-to-use-array-map-with-tuples-in-typescript#answer-57913509。这是合并然后恢复的。
为了更好地理解这个语法[...Fns]
请参阅文档可变元组类型 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#variadic-tuple-types
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)