Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Narrow type after assertion? #20682

Closed
aaronbeall opened this issue Dec 13, 2017 · 4 comments
Closed

Narrow type after assertion? #20682

aaronbeall opened this issue Dec 13, 2017 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@aaronbeall
Copy link

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.

@RyanCavanaugh
Copy link
Member

Same as #8655?

@aaronbeall
Copy link
Author

aaronbeall commented Dec 13, 2017

@RyanCavanaugh Looks like the same desired behavior for a different use case (using an assert() function)... in this case I'm saying can we treat the existing assertion syntax as a type-guard?

@aaronbeall
Copy link
Author

aaronbeall commented Dec 13, 2017

I realize that checking for a property is not considered good enough to narrow the type

Oh, actually, I just saw that #10485 "Treat in operator as type guard" made the roadmap for 2.7! I think that gives me everything I wanted here?

if ("radius" in shape && shape.radius) {
  shape.radius // Ok?
}

@mhegazy mhegazy added the Duplicate An existing issue was already created label Jan 10, 2018
@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants