【发布时间】:2020-08-24 20:13:14
【问题描述】:
最初,我想键入redux'mapDispatchToProps-like 函数,但在处理函数数组(动作创建者)作为参数时遇到了困难。有一个 hacky 但有效的例子。我想知道它是否可以改进。
问题是返回类型不保留每个项目的类型,它被泛化为联合。
更新:问题在于在结果数组中保留每个函数的参数类型。
简而言之,下面的代码应该没有错误:
type F = (...x: any[]) => any
type Wrap<T extends F> = (...x: Parameters<T>) => void
const wrap = (fn: any) => (...a: any) => {fn(...a)}
// currently working solution
// the problem is K being too wide (number | string | symbol) for array index thus silenced
// // @ts-expect-error
// function main<Fs extends readonly F[]>(fs: Fs): {[K in keyof Fs]: Wrap<Fs[K]>}
// TODO: desired solution but not finished: every item in `fs` should be wrapped with `Wrap`
function main<Fs extends readonly F[]>(fs: Fs): [...Fs]
function main(fs: any) {return fs.map(wrap)}
const n = (x: number) => x
const s = (x: string) => x
const fs = main([n, s] as const)
// TEST PARAMETERS TYPES
fs[0](1)
fs[1]('1')
// @ts-expect-error
fs[0]('1')
// @ts-expect-error
fs[1](1)
// TEST RETURN TYPES
const _1: void = fs[0](1)
const _2: void = fs[1]('1')
// @ts-expect-error
const _3: number = fs[0](1)
// @ts-expect-error
const _4: string = fs[1]('1')
P.S: an open (as for 25-aug-2020) github issue 与我的解决方案 #1 的问题有关,所以它不是关于可变元组类型,而是关于 keyof ArrayType 对于数组索引类型来说太宽了
【问题讨论】:
标签: typescript