1

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?

Stav Alfi
  • 13,139
  • 23
  • 99
  • 171
  • 1
    Does this answer your question? [Typescript - Remove last element from Parameters tuple, currying away last argument](https://stackoverflow.com/questions/63789897/typescript-remove-last-element-from-parameters-tuple-currying-away-last-argum) – Brank Victoria Mar 31 '22 at 09:14

2 Answers2

3

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

Oblosys
  • 14,468
  • 3
  • 30
  • 38
  • How can I prevent losing the paramter names? – Stav Alfi Apr 01 '22 at 14:23
  • @StavAlfi What do you mean exactly? In the type `Test`, the labels `str` & `n` are the parameter names. (playground link was broken, but now it works) – Oblosys Apr 01 '22 at 14:41
  • @StavAlfi I guess you meant to put that comment on another answer? Anyway, regarding your deleted comment, the version above works with trailing optional arguments. – Oblosys Apr 01 '22 at 15:34
-1

First, reverse()

and

function aa(a1,...rest){
    console.log(a1,"",rest);
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45