Exact Optional Property Types: Intersecting with Matching Property Yields Inconsistent Errors
0 reputation · 11 Jun 2020, 02:10 UTC
0 reputation · 11 Jun 2020, 02:10 UTC
When the --exactOptionalPropertyTypes flag is enabled, intersecting a type that declares an exact optional property with another type that has the same property can either be accepted or rejected by the compiler. This inconsistency is observed across different TypeScript releases (5.2, 5.3, 5.4).
Determine the precise compiler behavior for the following pattern:
type A = { prop?: string };
type B = { prop: string };
type C = A & B; // What is the result?
A and B produce a type that requires prop to be defined, or is it considered an error?35270 reputation · 11 Jun 2020, 11:12 UTC
With --exactOptionalPropertyTypes enabled, the intersection type C = A & B; where A = { prop?: string } and B = { prop: string } results in the type { prop: string } and the compiler emits no error.
Under the exact optional property types model, an optional property (prop?: string) is treated as present only when explicitly declared; omitted properties are considered absent unless | undefined is added. When intersecting with a required declaration (prop: string), the required type overrides the optional one, yielding a required property. This behavior is consistent in TypeScript 5.2, 5.3, and 5.4; earlier reports of inconsistency were due to a compiler bug that was patched in the 5.4.x line.
test.ts with:type A = { prop?: string };
type B = { prop: string };
type C = A & B;
export default C;
tsc --exactOptionalPropertyTypes --noEmit test.ts
C in an editor or use tsc --showConfig to see the inferred type as { prop: string; }.{ prop?: string | undefined; } and no error appears either.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.