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
orfoo = "foo" and bar = "bar"How can I accomplish that with typescript?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With