Closed
Description
TypeScript Version: 2.9
Search Terms: assert, isUndefined, strictNullChecks, assertion
Code
function assert(foo: boolean, message: string = "") {
if (!foo) {
console.error("Assertion failure:", message);
throw "Assertion failure: " + message;
}
}
class Bar {
foo?: number;
baz(): void {
assert(this.foo != undefined); //or assert(!isUndefined(this.foo))
this.foo += 7;
}
}
Expected behavior:
tsc
should support this declarative form of coding, and ship with support for assert(expr)
which satisfies the compiler's requirement of !!expr
. Obviously support for user-defined assertions would be extremely complicated as it would require tsc's analysis to leave the scope it is in, but an in-built assert
function would work around that.
Actual behavior:
An error about possibly undefined foo
is thrown with strictNullChecks
on, pointing to the line this.foo += 7;
.
Playground Link:
Related Issues: