Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 577
Gustavo Lopes Avatar asked Oct 29 '25 05:10

Gustavo Lopes


1 Answers

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;
like image 197
Madara's Ghost Avatar answered Oct 30 '25 22:10

Madara's Ghost