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;
}


This content originally appeared on DEV Community and was authored by Matt Gregg

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;
}

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;
}

Use nullish coalescence:

function foo(param?: SomeObject) {
  const { stuff } = param ?? {};
}

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

function foo(param?: SomeObject) {
  anotherFunction(param?.stuff);
}

All of these work and will handle param being undefined.


This content originally appeared on DEV Community and was authored by Matt Gregg


Print Share Comment Cite Upload Translate Updates
APA

Matt Gregg | Sciencx (2021-05-06T20:52:08+00:00) Destructure Optional Params in Typescript. Retrieved from https://www.scien.cx/2021/05/06/destructure-optional-params-in-typescript/

MLA
" » Destructure Optional Params in Typescript." Matt Gregg | Sciencx - Thursday May 6, 2021, https://www.scien.cx/2021/05/06/destructure-optional-params-in-typescript/
HARVARD
Matt Gregg | Sciencx Thursday May 6, 2021 » Destructure Optional Params in Typescript., viewed ,<https://www.scien.cx/2021/05/06/destructure-optional-params-in-typescript/>
VANCOUVER
Matt Gregg | Sciencx - » Destructure Optional Params in Typescript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/06/destructure-optional-params-in-typescript/
CHICAGO
" » Destructure Optional Params in Typescript." Matt Gregg | Sciencx - Accessed . https://www.scien.cx/2021/05/06/destructure-optional-params-in-typescript/
IEEE
" » Destructure Optional Params in Typescript." Matt Gregg | Sciencx [Online]. Available: https://www.scien.cx/2021/05/06/destructure-optional-params-in-typescript/. [Accessed: ]
rf:citation
» Destructure Optional Params in Typescript | Matt Gregg | Sciencx | https://www.scien.cx/2021/05/06/destructure-optional-params-in-typescript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.