'how to reference all parameters except last in typescript

Similar to this quesiton: how to reference all parameters except first in typescript

But here, I Want to get all parameters except the last one.

The accepted answer over there did not work in this use case.

Is there a way to do that?



Solution 1:[1]

This can be done with an inferred rest type, but it gets slightly complicated by trailing optional arguments, which break the rest-type matching. To deal with this, the parameters can be wrapped in non-optional singleton tuples, which can be unwrapped in the resulting initial parameters.

type Wrap<T> = {[K in keyof T]-?: [T[K]]}
type Unwrap<T> = {[K in keyof T]: Extract<T[K], [any]>[0]}

type InitialParameters<F extends (...args: any) => any> =
  Wrap<Parameters<F>> extends [...infer InitPs, any] ? Unwrap<InitPs> : never

const f1 = (str: string, n?: number, b?: boolean) => {}

const f2 = (to: string, overrides?: number) => {}

type Test1 = InitialParameters<typeof f1>
// [str: string, n: number | undefined]

type Test2 = InitialParameters<typeof f2>
// [to: string]

TypeScript playground

Solution 2:[2]

First, reverse()

and

function aa(a1,...rest){
    console.log(a1,"",rest);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 General Grievance