Search code examples
typescriptdestructuring

Destructuring in Typescript with undefined values


I have 2 objects:

const a = {
    foo: "foo",
    bar: "bar",
}

const b = {
    foo: "fooooo",
}

I want to use destructuring in a method with default undefined values, like so:

const c = a or b; // I don't know which one 

Then I want to do:

const { foo, bar } = c;

And I want that

  • foo = "fooooo" and bar = undefined or
  • foo = "foo" and bar = "bar"

How can I accomplish that with typescript?


Solution

  • TypeScript won't be smart enough to deduct that {foo: string, bar: string} | {foo: string} can be written as {foo: string, bar?: string}, so you'll need to type c yourself as follows:

    const c: { foo: string, bar?: string } = Math.random() > .5 ? a : b; // doesn't matter which
    const { foo, bar } = c;