6

Suppose i have these types

    /** Types of a function's arguments */
export type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;

export type ExcludeQueryParams<T> = { [P in keyof T]: T[P] extends PagingParameters ? never : T[P] }

Then i have this code to extract the types of the arguments for a function

function test(query: PagingParameters, as: number, f: string) {
    return 1;
}

type argTypes = ArgumentTypes<typeof test>
type result = ExcludeQueryParams<argTypes>

Above, argTypes will equal [PagingParameters, number, string]

What i am trying to do is extract the PagingParameters type from the array so result is [number, string], however using ExcludeQueryParams the result is [never, number, string].

How can achieve this properly without the final type array containing the never type?

joeblow
  • 61
  • 1
  • 3

1 Answers1

0

You can create the type FilterFirstElement, which will exclude an array's first element. It uses Generics (any variety of an array) and the keyword infer (refers to the rest of the array's parameters).

Here is a code sample:

type FilterFirstElement<T extends unknown[]> = T extends [unknown, ...(infer R)]
  ? R
  : [];

type arr1 = FilterFirstElement<[]>; // []
type arr2 = FilterFirstElement<[string]>; // []
type arr3 = FilterFirstElement<[string, number]>; // [number]
type arr4 = FilterFirstElement<[string, number, boolean]>; // [number, boolean]
Jan Hrdý
  • 11
  • 2
  • 2
    Please read [answer] and [edit] your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post. – Adriaan Oct 11 '22 at 13:11