Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If statement in typescript is not catching undefined value as it should?

I have the following function my point argument is optional and I am handling/(catching) it in the first if statement but the issue is type script is still concerned the in the second block after the if that point argument can be possible undefined, what is even more awkward is the optionB that is optional as well is not giving the undefined error how to fix this without having to use the ! operator ?

// Sec | Min Sec && Min support both types of time units min and secs
  const timeArray = (arr: (string | number)[] | number[], optionA: string, optionB?: string, point?: number): string[] => {
    // if no point or second value return singlar array
    if (!point && !optionB) {
      return Array.from(arr, (el) => el + ` ${optionA}`);
    }
    // if all argumnet are avalibale then return a doual time value array
    return Array.from(arr, (el, i) => el + ` ${i <= point! ? optionA : optionB}`);
  };

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if(!point && !optionB)

This IF block would be skipped if either point or optionB is undefined.

Let’s say optionB is undefined..——————(1)
The first block is skipped, as per your condition.

obviously, TS will point out to you that optionB is possibly undefined in the second block (assumption (1))

Now Lets say point is undefined………………..(2)
The first block is skipped, as per your condition.

TS will again point to you that point is possibly undefined in the second block (assumption (2)).

This is why you see both linting errors.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading