DEV Community

Matt Gregg
Matt Gregg

Posted on • Originally published at codegregg.com

3 1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more