Skip to content

Type guard narrowing doesn't occur in else branch of conditionals with multiple conditions #1270

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

Closed
danquirk opened this issue Nov 25, 2014 · 1 comment · Fixed by #5442
Closed
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@danquirk
Copy link
Member

var x: string|number;
// no error, x is number in else branch
var r4 = typeof x === "string" ? x.substr : x.toFixed; 

// error, x is string|number in else branch
var r5 = typeof x === "string" && typeof x === "string" ? x.substr : x.toFixed; 

Same behavior occurs in if/else. I believe the error is this logic in narrowTypeByAnd:

// The assumed result is false. This means either the first operand was false, or the first operand was true
// and the second operand was false. We narrow with those assumptions and union the two resulting types.
return getUnionType([
    narrowType(type, expr.left, /*assumeTrue*/ false),
    narrowType(narrowType(type, expr.left, /*assumeTrue*/ true), expr.right, /*assumeTrue*/ false)
]);
@danquirk danquirk added the Bug A bug in TypeScript label Nov 25, 2014
@vladima
Copy link
Contributor

vladima commented Nov 25, 2014

More precisely:

  • first case narrowType(type, expr.left, /*assumeTrue*/ false), correctly yields number
  • when evaluating second branch we first narrow type assuming that check for lhs should succeed- this yields string. After that we'll try to narrow this type assuming that check for rhs fails - in process of doing this we'll invoke subtractPrimitiveTypes to subtract string from string. Intuitively this should return empty object type or union type with 0 constituents, however now subtractPrimitiveTypes works only for union types and for other kinds of types it will just return type itself - string.

Result type that will ultimately be returned will be number | string

@mhegazy mhegazy added this to the TypeScript 1.5 milestone Dec 2, 2014
@mhegazy mhegazy modified the milestones: Community, TypeScript 1.5 Jan 30, 2015
@weswigham weswigham self-assigned this Oct 28, 2015
@mhegazy mhegazy modified the milestones: TypeScript 1.8, Community Nov 11, 2015
@mhegazy mhegazy added the Fixed A PR has been merged for this issue label Nov 11, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
4 participants