'What is the best approach to declare variable in typescript for class assignment?

I don't want to declare accountHandler as any it is not good practice. What is a better approach to create class variable when you have to assign it to class in the constructor.

main.ts

{
 private accountHandler: any= {};
 private requestLOB: string[] = [];


    constructor() {
        if (process.env.ENABLEBackendSwitch === "true") {
            this.accountHandler = new AccountBalanceHandlerV2();
        } else {
            this.accountHandler = new AccountBalanceHandler();
        }
    }


Solution 1:[1]

Typescript will actually infer the type of fields initialized in constructors. So if you don't have any annotation, it will be infered.

class X {
    private accountHandler;
//           ^?  X.accountHandler: AccountBalanceHandlerV2 | AccountBalanceHandler
    constructor() {
        if (process.env.ENABLEBackendSwitch === "true") {
            this.accountHandler = new AccountBalanceHandlerV2();
        } else {
            this.accountHandler = new AccountBalanceHandler();
        }
    }
}

Playground Link

But the best practice is to actually be explicit about the type:

class X {
    private accountHandler: AccountBalanceHandlerV2 | AccountBalanceHandler
    constructor() {
        if (process.env.ENABLEBackendSwitch === "true") {
            this.accountHandler = new AccountBalanceHandlerV2();
        } else {
            this.accountHandler = new AccountBalanceHandler();
        }
    }
}

Playground Link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Titian Cernicova-Dragomir