Skip to content

Inconsistent narrowing from unions with overlapping possibly-optional properties #26551

Closed

Description

TypeScript Version: 3.1.0-dev.20180813

Search Terms:
type guard, narrowing, union, optional, overlapping

Code

// --strictNullChecks on, please
declare function guard(w: any): w is { a: string | undefined };

declare const x: { a?: string };
x.a; // string | undefined
if (guard(x)) {
  x.a; // string | undefined
}

declare const y: { a?: string } | { a: string };
y.a // string | undefined
if (guard(y)) {
  y.a; // string ??
}

Expected behavior:
With --strictNullChecks on: after being narrowed by the type guard, both x.a and y.a should be string | undefined.

Actual behavior:
The type guard narrows y to {a: string} for some reason. The {a?: string} constituent is presumably being eliminated from the union, but I'm not sure why.

Playground Link:
Link

Related Issues:
Didn't find anything obvious... maybe #11403 or #17561?

Noticed in a comment in #21732.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions