Reputation: 764
I am trying to create tuple type that contains two elements, the first being a function and the second the parameters it takes. I have been somewhat successful by creating a generic type CallbackTuple
. Ideally I would like to be able to infer the second element of the tuple without explicitly having to pass the type argument typeof a
, how would I do this?
function a({ foo, bar }: { foo: string; bar: number }) {
return { foo, bar };
}
type CallbackTuple<
PluginFn extends (...args: any[]) => any = (...args: any[]) => any
> = [PluginFn, ...Parameters<PluginFn>];
const cbTuple1: CallbackTuple<typeof a> = [a, { foo: "", bar: 1 }]; // Valid
const cbTuple2: CallbackTuple<typeof a> = [a, { foo: "" }]; // Property 'bar' is missing
const cbTuple3: CallbackTuple = [a, { foo: "" }]; // I want this to type check properly
Upvotes: 1
Views: 2501
Reputation: 249466
You can't do this without an extra function do help with inference. Variables can either have their types specified or inferred. There is no way to have just some parts of a variable type inferred.
function makeCallbackTuple<T extends (...args: any[]) => any>(p: CallbackTuple<T>) {
return p
}
const cbTuple1 = makeCallbackTuple([a, { foo: "", bar: 1 }]); // Valid
const cbTuple2 = makeCallbackTuple([a, { foo: "" }]); // Property 'bar' is missing
Upvotes: 1