Skip to content

If a union has undefined an initializer will remove null or void from the union as well. #14406

@krisselden

Description

@krisselden

TypeScript Version: locally with 2.2.1 and in playground

Code

with strictNullChecks option in playground

type Opaque = {} | null | void | undefined;

class VersionOne {
  x: Opaque;
  constructor(x: {} | null | void = null) {
    this.x = x;
  }
}

new VersionOne(<Opaque>2);

class VersionTwo {
  constructor(public x: {} | null | void = null) {
  }
}

new VersionTwo(<Opaque>1);

class VersionThree {
  constructor(public x: Opaque = null) { // null is not assignable to {}
  }
}

new VersionThree(<Opaque>1); // null is not assignable to {} | undefined

class VersionFour {
  constructor(public x: number | void | undefined = 1) {
  }
};

let y = new VersionFour().x + 5; // should error but does not

class VersionFive {
  constructor(public x: number | void = 1) {
  }
};

y = new VersionFive().x + 3; // plus cannot be applied to number | void

Expected behavior:
if undefined is specified explicitly by a union the initializer should not remove the void or null along with undefined.

I would expect VersionThree to behave like VersionTwo and VersionFour to be like VersionFive

Actual behavior:
adding undefined to the type union causes the resulting type to lose null or void.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs InvestigationThis issue needs a team member to investigate its status.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions