Home > Net >  What is the best approach to declare variable in typescript for class assignment?
What is the best approach to declare variable in typescript for class assignment?

Time:03-02

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();
        }
    }

CodePudding user response:

Instead of any you can use AccountBalanceHandlerV2 | AccountBalanceHandler. But you actually don't even need to set the type as TypeScript will infer the value for you based on what you assign it to in the constructor (so long as you remove your default assignment):

class A {
  private accountHandler;


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

accountHandler is inferred to be of type AccountBalanceHandlerV2 | AccountBalanceHandler.

CodePudding user response:

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

  • Related