1

The code is like this:

class MyClass {
  getValue() {
    // some code here...
  }
}

const IS_ENABLED = process.env.IS_ENABLED || false;
const myClass = IS_ENABLED ? new MyClass() : null;

function getValue() {
  if (!IS_ENABLED) return false;

  return myClass.getValue();
}

Now at this point, TypeScript is giving error (for myClass.getValue()):

Object is possibly 'null'.

But, since I've checked the condition, I'm sure it's not null.

Is there any way for TypeScript to handle it?

2
  • I tried to reproduce your code , but I can't see the error. Commented Jun 18, 2019 at 20:22
  • @YakovFain That's probably because I had not defined MyClass in my code. I have done that. Also, I'm using strict checking in my 'tsconfig.json' Commented Jun 19, 2019 at 6:24

2 Answers 2

2

Typescript will not keep track of variables that are related in this way. There are a number of patterns that act as type guards and change the type of a variable.

In this case since IS_ENABLED and myClass are very much related, you can just check the if myClass is undefined.

const IS_ENABLED = process.env.IS_ENABLED || false;
const myClass = IS_ENABLED ? new MyClass() : null;

function getValue() {
    if (!myClass) return false;

    return myClass.getValue();
}

Or you could use a discriminated union (this might be useful if you have multiple myClass type like varaibles):

const config = (process.env.IS_ENABLED || false) ? {
    IS_ENABLED: true as const,
    myClass: new MyClass(),
    myClass2: new MyClass()
} : {
    IS_ENABLED: false as const,
}

function getValue() {
    if (!config.IS_ENABLED) return false;
    config.myClass2.getValue();
    return config.myClass.getValue();
}
Sign up to request clarification or add additional context in comments.

1 Comment

1st example works. Yet I was expecting better from TypeScript to detect the type.
0

Type Guards allow you to narrow down the type of an object within a conditional block. You can use instanceof to make Typescript knows its type.

const IS_ENABLED = process.env.IS_ENABLED || false;
const myClass = IS_ENABLED ? new MyClass() : null;

function getValue() {
  if (!IS_ENABLED) return false;
  if (myClass instanceof MyClass) {
    return myClass.getValue();
  }
  return false;
}

For details please check this.

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.