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 :
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.