Skip to content

Support asserting !isUndefined/!isNullOrUndefined #23717

Closed
@mqudsi

Description

@mqudsi

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:

https://www.typescriptlang.org/play/#src=function%20assert(foo%3A%20boolean%2C%20message%3A%20string%20%3D%20%22%22)%20%7B%0D%0A%20%20%20%20if%20(!foo)%20%7B%0D%0A%20%20%20%20%20%20%20%20console.error(%22Assertion%20failure%3A%22%2C%20message)%3B%0D%0A%20%20%20%20%20%20%20%20throw%20%22Assertion%20failure%3A%20%22%20%2B%20message%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Aclass%20Bar%20%7B%0D%0A%20%20%20%20foo%3F%3A%20number%3B%0D%0A%0D%0A%20%20%20%20baz()%3A%20void%20%7B%0D%0A%20%20%20%20%20%20%20%20assert(this.foo%20!%3D%20undefined)%3B%20%2F%2For%20assert(!isUndefined(foo))%0D%0A%20%20%20%20%20%20%20%20this.foo%20%2B%3D%207%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions