Closed
Description
Bug Report
When I use discriminating unions I expect that only one of them will be allowed by TS, not their intersection
🔎 Search Terms
Discriminating union
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about union types
⏯ Playground Link
Playground link with relevant code
💻 Code
type Common = {foo: string};
type A = Common & {a: string};
type B = Common & {b: string};
type Params = Common | A | B;
// expect error here
const bar: Params = {foo: '123', a: '123', b: '123'};
const myFn = (params: Params) => {}
// expect error here
myFn({foo: '123', a: '123', b: '123'})
🙁 Actual behavior
TS allows using both fields from A and B types
🙂 Expected behavior
TS should treat this as an error
Also if I try to set never
for fields that I don't want to be set, it doesn't work
type A = Common & {a: string, b: never};
type B = Common & {a: never, b: string};
There's a workaround for this, but it looks hacky
type A = Common & {a: string, b?: never};
type B = Common & {a: never, b: string};
Activity
MartinJohns commentedon Jun 28, 2021
Duplicate of #20863. And you also want #12936.
Additional properties is simply something you have to expect and deal with if you want to write robust code, given the current design of the language.
alexeyMohnatkin commentedon Jun 28, 2021
@MartinJohns thank you.
For those who are looking for an answer: