Issue
In TypeScript it's possible for a function-argument to have a type based on another, generic argument:
// foo(true, (v /* will be 1*/) => void 0)
// foo(false, (v /* will be 2*/) => void 0)
const foo = <T extends boolean>(a: T, cb: (v: T extends true ? 1 : 2) => void) => {}
On the other hand, you can get the type of a function via typeof
and the Parameters using Parameters<typeof foo>
:
const foo = (a: number, b: string) => {}
// Evaluates to (cb: (a: number, b: string) => void)
const baz = (cb: (...args: Parameters<typeof foo>) => void) => {}
How can I do this with functions where generics are used and the original function definition is unknown, I'm looking for something like this:
// This function may be unknown or have overloads.
const foo = <T extends boolean>(args: T, cb: (v: T extends true ? 1 : 2) => void) => {}
const bar = <T extends Parameters<typeof foo>[0]>(
args: T,
// Doesn't work, just an example.
// I imagined something like "give me the type of function 'foo' for when the first argument is 'T'"
cb: Parameters<(typeof foo)[T]>[0]
) => {}
bar(true, (v /* should be 1 */) => void 0)
Solution
What you're looking for are called instantiation expressions, which were recently added in 4.7:
const foo = <T extends boolean>(args: T, cb: (v: T extends true ? 1 : 2) => void) => {}
const bar = <T extends Parameters<typeof foo>[0]>(
args: T,
cb: Parameters<typeof foo<T>>[1]
) => {}
bar(true, (v /* should be 1 */) => void 0);
Answered By - caTS
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.