Skip to content

Narrow type after assertion? #20682

Closed
Closed
@aaronbeall

Description

@aaronbeall

TypeScript Version: 2.7.0-dev.201xxxxx

Would it be possible to treat an assertion like a type-guard and narrow the type within blocks that are "guarded" by an assertion?

For example:

Code

type Square = { size: number; }
type Circle = { radius: number; }
type Shape = Square | Circle;

declare const shape: Shape;
if ((shape as Circle).radius) {
  shape.radius // Error: Property 'radius' does not exist on type 'Square'
  (shape as Circle).radius // Ok, but seems redundant
}

But you could consider the (shape as Circle).radius like the user saying:

isCircle(shape) && shape.radius
// or at least
hasRadius(shape) && shape.radius

I realize that checking for a property is not considered good enough to narrow the type, but if the user has explicitly asserted the type it would be convenient if control flow could keep track of that in downstream code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions