Max Yankov
Max Yankov

Reputation: 13327

How can I omit a first parameter from the function parameters type?

I have a sendMessage from a third-party library function with parameters:

function sendMessage(chatId: number | string, text: string, extra?: tt.ExtraEditMessage)

I want to create another function that will send a message to a specific user. I want this function to have all parameters of the original function:

export async function sendMessageToAdmin(text: string, extra?: tt.ExtraEditMessage)

But I want for this type declaration to be DRY and update automatically when I update a third-party dependency, so I can use Parameters utility type:

type SendMessageParameters = Parameters<sendMessage>

export async function sendMessageToAdmin(...parameters: SendMessageParameters)

However, I also want to omit the first parameter, chatId, since I'll be setting it on my own. Unfortunately, Omit utility type only works for properties and not tuple members.

How can I construct a type that will have all parameters of a function instead of a first one, or one with specific name?

Upvotes: 2

Views: 2778

Answers (2)

You need just to return Tail of tuples

function sendMessage(foo: number, baz: string, bar: number[]) { }

type Tail<T extends unknown[]> = T extends [infer Head, ...infer Tail] ? Tail : never;

function otherFunc(...parameters:Tail<Parameters<typeof sendMessage>>){} // baz: string, bar: number[]

Upvotes: 5

Max Yankov
Max Yankov

Reputation: 13327

I was able to do it by modifying the original Parameters:

type ParametersExceptFirst<T extends (...args: any) => any> = T extends (
    ignored: infer _,
    ...args: infer P
) => any ? P : never

Upvotes: 1

Related Questions