TypeScript中是否有内置方法对Parameters元组进行切片以排除首个参数?
Unfortunately, as of TypeScript 5.x, there is no built-in utility type specifically for slicing tuples (like extracting all elements except the first one). The built-in utilities such as Omit work exclusively with object types, not tuples, so they won’t help here.
That said, creating a custom type to handle this is actually simpler than you might think—you don’t need an overly complex implementation. Here’s the standard, clean way to extract all elements from a tuple except the first:
type RemoveFirstFromTuple<T extends any[]> = T extends [infer _, ...infer Rest] ? Rest : never;
Let’s walk through how this works with your example:
- Use
Parameters<typeof SomeFunction>to get the full tuple of your function’s parameters. - Pass that tuple into
RemoveFirstFromTuple, which uses conditional type inference (infer) to split the tuple into the first element (we name it_since we don’t need to use it) and the remaining elements (Rest).
Here’s a practical usage example:
function SomeFunction(a: string, b: number, c: boolean) { /* ... */ } // Extract all parameters except the first one type ArgsExceptFirst = RemoveFirstFromTuple<Parameters<typeof SomeFunction>>; // ArgsExceptFirst resolves to [number, boolean]
If you ever need to skip more than just the first element (say, skip the first 2 parameters), you can extend this pattern with a recursive type:
type SkipFirstN<T extends any[], N extends number, Accumulator extends any[] = []> = Accumulator['length'] extends N ? T : T extends [infer _, ...infer Rest] ? SkipFirstN<Rest, N, [...Accumulator, _]> : never; // Usage: skip the first 2 parameters of SomeFunction type ArgsExceptFirstTwo = SkipFirstN<Parameters<typeof SomeFunction>, 2>; // ArgsExceptFirstTwo resolves to [boolean]
While it’s a shame there’s no built-in tool for this, the custom type is lightweight, reusable, and leverages core TypeScript type system features (conditional types and inference) that you’ll encounter often in type-level programming.
内容的提问来源于stack exchange,提问作者RobertAKARobin

