...rest: T[] Rest Parameters

Last updated: 2026-10-22

...rest: T[] Rest Parameters

Rest parameters (...scores: number[]) collect all remaining arguments into a real array, letting a function accept any number of same-typed arguments — the type-safe replacement for arguments.

GroupFunctions & Classes
KindSyntax
Strict modeNot required

ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.

📝 Syntax

function average(...scores: number[]): number {
  if (scores.length === 0) return 0;
  return scores.reduce((sum, s) => sum + s, 0) / scores.length;
}

// Positional + rest: the rest parameter must be last
function logRequest(method: string, ...fields: string[]): void;

⚙️ Parameters

...scores: number[]Rest parameter: all remaining arguments are collected into a number[]; must be the last item in the list

Returns:Same as ordinary functions: annotate explicitly or infer from the body; a rest parameter changes nothing about return typing.

▶ Example

Edit the code below and click Try it to see the transpiled result:

Output:

84.3
97.5
0

(Runtime output after transpilation; average("90") is a compile error — rest elements must be number)

💡 Notes

ℹ️ Info Rest parameters are real arrays at runtime — map/filter/reduce work directly. Far safer than the legacy arguments object (array-like and untyped).
⚠️ Note ...args: any[] throws away all element types; prefer concrete element types, or a generic tuple ...args: T to keep positions typed.
💡 Tip Tuple types can pin down rest parameters: ...args: [name: string, retries: number] means argument 1 must be string and argument 2 number.
More cases coming soon.

📚 Related tutorials

❓ FAQ

Q ...scores: number[] vs scores: number[] — what's the difference?
A The latter is one array parameter: average([90, 85]). The former accepts any number of number arguments: average(90, 85). If callers already hold an array, a plain array parameter fits better.
Q Can a rest parameter go in the middle?
A No. It must be last — "rest" by definition collects everything after it; the compiler rejects it anywhere else.
Q What are generic rest parameters for?
A <T extends any[]>(...args: T) collects arguments as a tuple, preserving each position's type — the key trick for wrap/decorate utilities that forward arguments.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏