1

This might be duplicated, but I cannot find an answer.

I have this type:

type A = {
    prop2: string;
    prop1: string;
} | {
    prop3: string;
    prop1: string;
}

As you can see, it has a shared prop and 2 different props. But then I can use it like this:

const a: A = {
  prop1: '',
  prop2: '',
  prop3: '',
};

And it works!

But then I need to check that a has prop2 and prop3 to use it:

a.prop1 = '';
// @ts-expect-error
a.prop2 = ''; // ERROR
if ('prop2' in a) {
  a.prop2 = ''; // OK
}

Why does typescript let me declare both props? I would expect it to be as strict as when using the variable. The original example was a React component and it let me pass all props.

BTW, I cannot add a prop4, only 1, 2 and 3.

Sergio Tx
  • 3,706
  • 1
  • 16
  • 29

1 Answers1

2

In 2023, it is still a relevant question that doesn't have a real acceptable answer that doesn't require some complex work around. This one by jcalz should help you.

Florent M.
  • 1,107
  • 1
  • 6
  • 14
  • 2
    Welcome to Stack Overflow! If a question is answered by the answers to a previous question, the way we do things here, we don't post an *answer* to the question with a link to the other answer. Instead, we vote to close as a duplicate of that other question (which points the OP at those answer), optionally providing a comment providing more context. Even though you don't have enough rep yet for your VTC to actually count toward closing the question (doesn't look like that'll take you long), it still flags up the previous question and others can finish the process for you. – T.J. Crowder May 17 '23 at 08:46
  • 2
    Oh sorry I didn't realized that. Thank you ! – Florent M. May 17 '23 at 08:48
  • https://github.com/Microsoft/TypeScript/issues/14094#issuecomment-373629568 This issue has also some information. – Sergio Tx May 17 '23 at 09:56