Closed as not planned
Description
π 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
π» 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.