Skip to content

TypeScript 2.2.1 generates surprising null checking error #14487

Closed

Description

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'.

Activity

  1. BurtHarris commented on Mar 6, 2017

    @BurtHarris
    Author

    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; }
  2. RyanCavanaugh commented on Mar 6, 2017

    @RyanCavanaugh
    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

  3. sandersn commented on Mar 6, 2017

    @sandersn
    Member

    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.

  4. added
    Fixed
    on Mar 8, 2017
  5. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugFixed

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions