Skip to content

Assertions do not narrow types when used as operand of the comma operator. #41264

Closed
@RebeccaStevens

Description

@RebeccaStevens

TypeScript Version: 4.1.0-dev.20201026

Search Terms: assert comma operator

Code

foo1 and foo2 should be equivalent but the assertion in foo2 does not narrow they typing of param.

declare function assert(value: any): asserts value;

function foo1(param: number | null | undefined): number | null { 
  const val = param !== undefined;

  if (val) {
    assert(param !== undefined);
    return param
  } else {
    return null;
  }
}

function foo2(param: number | null | undefined): number | null { 
  const val = param !== undefined;
  return val ? (assert(param !== undefined), param) : null;
                                          // ^^^^^ Still typed as number | null | undefined
}

Expected behavior:

No errors.

Actual behavior:

Type 'number | null | undefined' is not assignable to type 'number | null'.
  Type 'undefined' is not assignable to type 'number | null'.(2322)

Playground Link: https://www.typescriptlang.org/play?ts=4.1.0-dev.20201026#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXygGdCQYMAKANygmRAC4DUBPASkaJLMPmtpADcAWABQolOmx4kOHAEZyAB1hQAto1TJVAI1LwAPvE0QIB+GlCIsqEMHZGtumGeOmA3vFHx4YPIQy8NPAAvPDKMGrwAITBoRYgVjbAwmIi3liI8FQ0rPBuXt4ExKQU4ZExcaiW1rasKYXwcBjIMPhlqgUAvvAgECR5Bd5NLfiu9fCdopOpEpi4+IiyAExKKuoOOnqGrmbxibUajlsOJnmeaT5+AXwhYWvRseZVCTXJBcOtgaYA-FmcJasIqoHpVqklWAAaO5A3KHEzjBqIpHIlGo+AAenR8AAerjcfAAMrYU4YZiKWxFDZOFzIU6GPavKZAA

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions