0

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();
        }
    }
1
  • 1
    Shouldn’t it just be a union type of AccountBalanceHandler | AccountBalanceHandlerV2? Commented Mar 1, 2022 at 19:55

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

yes i tried that first thing but it throws error ` error TS7008: Member 'accountHandler' implicitly has an 'any' type.
@hussain Maybe you're on an older version of TypeScript. It was added a few versions back. Just set the type explicitly to AccountBalanceHandlerV2 | AccountBalanceHandler. Here's a TypeScript playground showing that the type can be inferred on newer versions:
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.