TypeScript 'never' on class member in catch?

TypeScript version 2.2.1.

I just started trying TypeScript and keep getting an error that I don't understand. I have set strictNullChecks to true because I want to determine which types can be nullified. So I have this class:

class Core {
    client: MessagesClient | null;

    connect(server: string, port: number, connectionHandler: ConnectionHandler) {
        if(this.client) {
            this.client.disconnect(false, "New connection");
            this.client = null;
        }

        try {
            this.client = new MessagesClient(server, port);
            functionWhichCanThrow(); //I.e, lot of other code which I didn't include    
        } catch(exception) {
            let error = "Error while setting up connection: " + exception;
            if(this.client) {
                this.client.disconnect(true, error);
                this.client = null;
            }
        }
    }
}

For some reason, inside the catch statement, the TypeScript compiler insists that this.client can never be anything other than null. Thus, this.client.disconnect throws an error: TS2339 error: the 'disconnect' property does not exist in the type 'never'.

I want to disconnect if it throws an exception that can occur at any point AFTER this client has been set.

this.client null , , , . - ?

EDIT:

class Test {
    test: string | null;

    doTest() {
        this.test = null;
        try {
            this.test = "test";
            throw new Error("");
        } catch(e) {
            if(this.test) //Visual Studio Code say that this is "null", not "string | null"
                this.test.replace("test", "error"); 
        }
    }
}
+4
1

try, . " ", test: this.test = null try. this.test = "...", , .

, ! post-fix:

this.test!.replace("test", "error");
+2

Source: https://habr.com/ru/post/1673207/


All Articles