Destructure Optional Params in Typescript

itwasmattgregg

Matt Gregg

Posted on May 6, 2021

Destructure Optional Params in Typescript

Sometimes you have a function with an optional Object argument that you want to destructure in the function. Like so:

interface SomeObject {
  option1: boolean;
  stuff: boolean;
}

function foo(param?: SomeObject) {
  const { stuff } = param;
}
Enter fullscreen mode Exit fullscreen mode

However you'll get an error because param could be undefined and TS doesn't like you trying to destructure something that's undefined. There are a couple ways around this...

Define a fallback in the initializer and don't use the ? optional identifier:

function foo(param: SomeObject = {}) {
  const { stuff } = param;
}
Enter fullscreen mode Exit fullscreen mode

Use nullish coalescence:

function foo(param?: SomeObject) {
  const { stuff } = param ?? {};
}
Enter fullscreen mode Exit fullscreen mode

Or just call the propery on the parameter directly with optional chaining:

function foo(param?: SomeObject) {
  anotherFunction(param?.stuff);
}
Enter fullscreen mode Exit fullscreen mode

All of these work and will handle param being undefined.

💖 💪 🙅 🚩
itwasmattgregg
Matt Gregg

Posted on May 6, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Implementing Signals from Scratch
javascript Implementing Signals from Scratch

September 28, 2023

Why you should use Typescript now
development Why you should use Typescript now

April 21, 2022