Typescript可以为受数组类型约束的通用rest参数推断元组类型。但这在我的情况下不起作用。我正在尝试传递一系列对[function, argument]
,并希望对参数和函数类型是否匹配进行类型检查。有可能吗?
type User = {
name: string
age: number
}
function eatNumber(a: number) { }
function eatString(a: string) { }
function eatUser(a: User) { }
type FuncAndArg<F extends (arg: any) => void> = [F, Parameters<F>[0]]
function callMany<F extends (arg: any) => void, T extends FuncAndArg<F>[]>(...pairs: T) { }
const jack = {
name: 'jack',
age: 23
}
//argument type not checked
callMany([eatNumber, jack], [eatString, jack], [eatUser, jack])
答案 0 :(得分:4)
是的,您可以使用rest参数来做到这一点。我用通用元组表示此方法,该元组表示callMany()
每个参数中第二个元素的类型,将pairs
参数指定为mapped tuple type,并依赖{{ 3}},以使编译器推断T
。像这样:
function callMany<T extends any[]>(
...pairs: { [I in keyof T]: [(a: T[I]) => any, T[I]] }
) { }
然后您可以像这样使用它:
callMany([eatNumber, jack], [eatString, jack], [eatUser, jack]); // error!
// ~~~~~~~~~ <-- User not assignable to number
callMany([eatNumber, 23], [eatString, jack], [eatUser, jack]); // error!
// ~~~~~~~~~ <-- User not assignable to string
callMany([eatNumber, 23], [eatString, "jack"], [eatUser, jack]); // okay
看起来像您想要的。好的,希望对您有所帮助。祝你好运!