🔎 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:
- The assertion is unconditionally called.
- 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.
🔎 Search Terms
asserts, return, void
🕗 Version & Regression Information
⏯ 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
🙁 Actual behavior
ais not narrowed totrue.This is odd because:
🙂 Expected behavior
I expect
ato be narrowed totrue.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:
With the
voidoperator, the type assertion is ignored.Even when occurring as the parameter for an
await,yield, orreturnstatement, the type assertion is discarded.