Why do assertion methods work on private class members only when intersecting with public members?

27 Views Asked by At

I am working with typescript. In my code, I am doing a type check via an assertion method for a private member. After research, It appears that you cannot type guard private class members. For example,

class Example {
    private num?: number;

    addToNumber(value: number) {
        this.assertNumberIsSet();
        this.num += value;
    }

    assertNumberIsSet(): asserts this is { num: number } {
        if (typeof this.num !== 'number') {
            throw TypeError('num is undefined');
        }
    }
}

In this example, the compiler will give the following error:

Property 'num' does not exist on type 'never'. The intersection 'this & { num: number; }' was reduced to 'never' because property 'num' exists in multiple constituents and is private in some.

However, when intersecting it's public members with "keyof", it works.

class Example {
    private num?: number;

    addToNumber(value: number) {
        this.assertNumberIsSet();
        this.num += value;
    }

    assertNumberIsSet(): asserts this is { [key in keyof this]: this[key] } & { num: number } {
        if (typeof this.num !== 'number') {
            throw TypeError('num is undefined');
        }
    }
}

Why does this second code example work, but not the first example? And would this be considered a valid solution for type guarding a private member?

0

There are 0 best solutions below