4

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?

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

2 Comments

The problem with this approach is that I don't want c to have the bar property. That's why I wanted the destructuring to return undefined, so c would still not have the bar property. I guess I'll have to create a wrapper function for that. Thank you
What do you mean? c might have the bar property whether you want to or not, if you set c to be a, it's going to have it... If not, it will get undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.