TypeScript类型交叉类型产生never类型的原因及特定交叉表达式结果的技术咨询
Let's break down why these two intersection type expressions produce their respective results—it all boils down to how TypeScript merges conflicting properties in intersection types.
1. Why { d: true; e: number; } & { d: false; e: number; } resolves to never
An intersection type (&) requires a value to satisfy all the types it combines. Let's zero in on the d property here:
- The first type enforces
dmust betrue - The second type enforces
dmust befalse
There’s no possible value that can be both true and false at the same time. Since the d property alone has no valid possible values, the entire combined type has zero valid values too. That’s exactly what the never type represents: a type with no possible runtime values.
Which is why in your code example, you can only assign an error-throwing expression to a variable of type DataTypeNever—there’s no legal value that fits the type:
type DataTypeNever = { d: true; e: number; } & { d: false; e: number; } let data: DataTypeNever = (() => { throw new Error })() // Only works because this never returns a valid value
2. Why { d: false; e: number; } & { d: false; e: string; } resolves to { d: false, e: never }
Here, the d property is consistent across both types—both specify d must be false. So TypeScript merges these into a single d: false property with no conflict.
Now look at the e property:
- The first type requires
eto be anumber - The second type requires
eto be astring
Just like with the d property in the first example, there’s no value that is both a number and a string. So the e property’s type becomes never (no valid values possible).
The combined type ends up as { d: false, e: never } because:
dhas a valid, consistent value (false)ehas no valid values (never)
Again, this is why you can only assign an error-throwing expression to the e property—there’s no valid number/string hybrid value to use:
type DataType = { d: false; e: number; } & { d: false; e: string; } let data: DataType = { d: false, e: (() => { throw new Error })() }
内容的提问来源于stack exchange,提问作者Jason

