Course contentsShow
← TypeScript
Lesson 261 of 1,7966. FunctionsFree lesson

Typing Rest Parameters Explicitly

Understand how to add explicit type annotations to rest parameters for precise control over accepted types.

Typing Rest Parameters Explicitly

What you'll learn: How to add precise type annotations to rest parameters so TypeScript knows exactly what types of arguments can be collected.


In the previous lesson, you learned that rest parameters gather multiple arguments into an array. By default, TypeScript infers their type, but sometimes you need explicit control over what types can be accepted.

Why Type Rest Parameters Explicitly?

When you don't annotate a rest parameter, TypeScript infers based on usage—which might be too loose or result in any[] if there's no context. Explicit typing lets you enforce exactly what values are allowed.

The Syntax

Just like typing a regular array parameter, you annotate a rest parameter with the array type syntax:

function logStrings(...messages: string[]): void {
  messages.forEach(msg => console.log(msg));
}

logStrings("Hello", "World");        // ✓ OK
logStrings("TypeScript", "Rocks");   // ✓ OK
// logStrings("Hi", 42);             // ✗ Error: number not assignable to string

The ...messages: string[] means "accept zero or more arguments, all of which must be strings."

Union Types in Rest Parameters

You can also use union types if you need flexibility:

function logMixed(...values: (string | number)[]): void {
  values.forEach(val => console.log(val));
}

logMixed("Age", 30, "Name", "Alice"); // ✓ OK
// logMixed(true);                    // ✗ Error: boolean not allowed

The Key Pattern

Think of rest parameter typing as: "What kind of array do I want these gathered arguments to form?" Whatever type you'd give that array is what you annotate after the rest parameter.

Key Takeaway: Explicitly typing rest parameters with syntax like ...params: Type[] gives you precise control over what argument types can be collected, preventing accidental misuse.