Skip to the solution
EasyFrontend10 min read

How do you type functions: optional, default and rest parameters?

525 views

The problem

Question presented to candidate: "Write a TypeScript function that takes a required argument, an optional one, one with a default value, and then any number of extra arguments. How do you type each kind, and what rules does the compiler enforce about them?"

What a strong answer should cover:

  • Optional parameter `b?: T`: callers may omit it, and inside the body its type is `T | undefined`
  • Default parameter `b = 1`: optional for callers, never `undefined` inside, type inferred from the default; the default applies to `undefined` but not to `null`
  • Rest parameter `...xs: T[]` (or a tuple type such as `...args: [x: number, y?: number]`), always last and only one
  • Order rules: a required parameter cannot follow an optional one (TS1016); a default before a required parameter is allowed but then not skippable
  • Function type expressions, spreading arrays into fixed parameters (needs a tuple, TS2556), and `Parameters<typeof f>`
  • Callback parameters should not be marked optional unless callers may really omit them

Code / implementation expected: Yes β€” one function using each parameter kind, with calls that pass and fail type checking.

  • functions
  • basics

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptOptional, default and rest parameters
TypeScriptFunction types, tuple rest, spreads and callback pitfalls

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 10 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

What are literal types?

Continue