Skip to content

TypeScript 2.2.1 generates surprising null checking error #14487

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
BurtHarris opened this issue Mar 6, 2017 · 3 comments · Fixed by #14498
Closed

TypeScript 2.2.1 generates surprising null checking error #14487

BurtHarris opened this issue Mar 6, 2017 · 3 comments · Fixed by #14498
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@BurtHarris
Copy link

BurtHarris commented Mar 6, 2017

TypeScript Version: 2.2.1

Effective type of argument p below seems to not match explicit declaration under tsc 2.2.1

Code

interface RuleContext  {
    _parent: RuleContext | undefined;
};

var  _ctx = { _parent: undefined};

function walk( p: RuleContext | undefined = _ctx ) {
    while (p) {
        p = p._parent; // Error w/ "strictNullChecks": true !
    }
}

Expected behavior:
Compiled w/o error under 2.1
Actual behavior:
Generates error:

index.ts(9,4): error TS2322: Type 'RuleContext | undefined' is not assignable to type 'RuleContext'.
  Type 'undefined' is not assignable to type 'RuleContext'.
@BurtHarris
Copy link
Author

BurtHarris commented Mar 6, 2017

Simple workarounds possible, just surprised at the change in behavior.

Another repro case:

var obj: Context = {
  parent: undefined
};

function working(p: Context | undefined) {
  while (p != null) {
    p = p.parent;
  }
}

function broken(p: Context | undefined = obj) {
  while (p != null) {
    p = p.parent;
  }
}

interface Context { parent: Context | undefined; }

@RyanCavanaugh
Copy link
Member

We changed the type of defaulted parameters from T | undefined to T in 2.2, but it seems wrong to strip out undefined from an explicitly-written type annotation

@sandersn
Copy link
Member

sandersn commented Mar 6, 2017

This is an intended result of #12033, but we should revisit whether to use the control-flow-narrowing mechanism instead of the one that shipped, which simply strips off | undefined from default-initialised and optional parameters.

@mhegazy mhegazy added the Fixed A PR has been merged for this issue label Mar 8, 2017
@mhegazy mhegazy added this to the TypeScript 2.3 milestone Mar 8, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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
Development

Successfully merging a pull request may close this issue.

4 participants