Skip to content

Instantly share code, notes, and snippets.

@johan
Created August 1, 2023 03:11
Show Gist options
  • Save johan/c29080fd8568853b4abf8a5b62bc0ef8 to your computer and use it in GitHub Desktop.
Save johan/c29080fd8568853b4abf8a5b62bc0ef8 to your computer and use it in GitHub Desktop.
Some ts utilities handy for well-typed reselect createSelector input functions.
/** Constructs a new function type from `F`, instead returning `R` */
export type Returns<F, R> = F extends (...args: any[]) => infer _
? (...args: Parameters<F>) => R
: never;
/**
* Given a (zero-indexed) positional argument number `n`
* and a function call signature generic type `F`,
* produce a well-typed function that selects that `n`th arg.
* @example
* const selectUser = selectArg<(state: Cache, user: User) => void>(1);
*/
export function selectArg<F extends (...args: any[]) => any>(
n: 0
): Returns<F, Parameters<F>[0]>;
export function selectArg<F extends (...args: any[]) => any>(
n: 1
): Returns<F, Parameters<F>[1]>;
export function selectArg<F extends (...args: any[]) => any>(
n: 2
): Returns<F, Parameters<F>[2]>;
export function selectArg<F extends (...args: any[]) => any>(
n: 3
): Returns<F, Parameters<F>[3]>;
export function selectArg<F extends (...args: any[]) => any>(
n: 4
): Returns<F, Parameters<F>[4]>;
export function selectArg<F extends (...args: any[]) => any>(
n: 5
): Returns<F, Parameters<F>[5]>;
export function selectArg<F extends (...args: any[]) => any>(
n: 6
): Returns<F, Parameters<F>[6]>;
export function selectArg<F extends (...args: any[]) => any>(
n: 7
): Returns<F, Parameters<F>[7]>;
export function selectArg<F extends (...args: any[]) => any>(
n: 8
): Returns<F, Parameters<F>[8]>;
export function selectArg<F extends (...args: any[]) => any>(
n: 9
): Returns<F, Parameters<F>[9]>;
export function selectArg<F extends (...args: any[]) => any, N extends number>(
n: number
): Returns<F, Parameters<F>[N]> {
return ((...args) => args[n]) as Returns<F, Parameters<F>[N]>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment