Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In TypeScript is there any "annotation" for methods to indicate a variable won't be null after exiting it?

In TypeScript with strict: true config, consider the following scenario:

export class A {

    a?: string;
    b?: number;

    init() {
        this.a = "";
        this.b = 0;
    }

    opA() {
        this.requireInit();
        const something = this.a.length; // Error here
    }

    opB() {
        this.requireInit();
        const something = this.b.toString(); // Error here
    }

    private requireInit() {
        if (this.a === undefined || this.b === undefined) {
            throw new Error("Call init before using this method");
        }
    }

}

Is there a way to mark requireInit method that after calling that method, a and b members is not undefined anymore so I do not have to use ! in every method? In C# there is a similar Attribute called MemberNotNull.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Making requireInit into an assertion function that asserts that its this definitely has those properties will do the trick.

class A {

    a?: string;
    b?: number;

    init() {
        this.a = "";
        this.b = 0;
    }

    opA() {
        this.requireInit();
        const something = this.a.length; // OK now
    }

    opB() {
        this.requireInit();
        const something = this.b.toString(); // OK now
    }

    private requireInit(): asserts this is { a: string, b: number } {
        if (this.a === undefined || this.b === undefined) {
            throw new Error("Call init before using this method");
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading