Skip to content

Type predicate silently ignored when used as non-statement expressionΒ #61105

Closed as not planned
@rotu

Description

@rotu

πŸ”Ž Search Terms

asserts, return, void

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type predicates

⏯ Playground Link

https://www.typescriptlang.org/play/?target=99&jsx=0&suppressImplicitAnyIndexErrors=false&ts=5.8.0-dev.20250202&ssl=19&ssc=1&pln=1&pc=1&q=5#code/GYVwdgxgLglg9mABAWwJ4EEDOmCmAnKACgEMAuRAIzjgBsdiwBKc47fKTRYxGTqPEDkQBvAFCIewRIQCExRoigALPHADuiMDg0BRPKryEARGDhRFAnDKOMA3KIC+o0aEiwEiHAA8AjCXJUtPRMIuIoGGwEJHZheDhQIHhIxPYSAPRpElkAegD8YRlZRdIADsR4xMjx+ApkFoKOzq7Q8EjeAEz+lNR0DApiEnTmXogAvOFYuFHyqYiFiNQlmDKIAJJc2DAA5loAJopKQnGYIDTmUHBciABu5TDEFHRcYPvKQlCoJUKsU+5IvJozIgIIcIABrHC7GSxeKJZKzeY5fLpTLFCSEMoVKpQGpcAI9YKNIA

πŸ’» Code

function myAssert(a: boolean): asserts a is true {
  if (!a) throw new Error("not true!");
}

function ex1(a: boolean) {
  myAssert(a);
  return a;
  //     ^?
  //        (parameter) a: true
}

function ex2(a: boolean) {
  let x = myAssert(a);
  //  oops! I assigned the result to a variable and the type assertion is not checked!
  return a;
  //     ^?
  //        (parameter) a: boolean
}

πŸ™ Actual behavior

a is not narrowed to true.

This is odd because:

  1. The assertion is unconditionally called.
  2. There is no warning to indicate that the type assertion has been ignored as in other cases where CFA can't work.

πŸ™‚ Expected behavior

I expect a to be narrowed to true.

Additional information about the issue

It seems not all expressions cause the type assertion to be ignored.

With the comma operator, for instance, the type assertion is still respected:

console.log(), myAssert(a), console.log();
// a is regarded as "true" here

With the void operator, the type assertion is ignored.
Even when occurring as the parameter for an await, yield, or return statement, the type assertion is discarded.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions