03 / 06

How to make a parameter of a function optional in TS?

Difficulty: 3/10
optional parameters, default values, function overloads

In TypeScript, every parameter is assumed to be required by the function. You can add a ? at the end of a parameter name to set it as optional.

Optional parameters must come after all non-optional parameters:

Scenario Questions

0-2 years experience

  1. 1We have a utility function formatDate(date: Date, format?: string). How would you implement it so callers can omit the format and get a default pattern?
  2. 2If you add a boolean flag?: boolean to a function, what does the compiled JavaScript look like for calls that omit that argument?
  3. 3What happens if you declare an optional parameter before a required one, and why does TypeScript warn about it?

2-5 years experience

  1. 1You added an optional config object to an existing function used throughout the codebase, and now some callers hit a runtime error. Walk me through how you'd debug the issue.
  2. 2Explain why using a default parameter value might be preferable to marking the parameter optional when the function also has overloads.
  3. 3We need a function that can accept either a string path or an options object where the options are optional. How would you type that in TypeScript?

5-8 years experience

  1. 1Our shared utilities library has many functions with several optional parameters. Discuss the trade‑offs of using a single options object versus multiple optional positional parameters, considering type safety and developer ergonomics.
  2. 2A performance‑critical function receives an optional callback. At scale we see extra overhead from undefined checks. How would you redesign the signature to minimize runtime cost while keeping type safety?
  3. 3When evolving a public API, you need to deprecate a required parameter and make it optional. How would you manage versioning and ensure downstream projects aren't broken?

8+ years experience

  1. 1You are leading a migration of a large monorepo from JavaScript to TypeScript. Many functions need new optional parameters without breaking legacy callers. Outline a strategy for introducing these optional parameters across the repo, including lint rules, automated refactoring, and cross‑team communication.
  2. 2Design a cross‑team SDK where functions have optional parameters that may be omitted in some target languages (e.g., JavaScript vs. Java). How would you model the API surface to keep consistency while respecting language‑specific optionality?

Follow-up Questions

  • What problems arise if an optional parameter is placed before a required one?
  • How does TypeScript emit code for a parameter with a default value versus a purely optional parameter?
  • When would you choose an options object over several optional positional parameters?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.