I've been working on creating a utility class that can help me throw an exception when something may be undefined, like
throwIfUndefined(array[index]).function()
and throwIfUndefined(obj.key).function()
. My goal is to streamline my code as using if conditions and manually throwing errors can get quite cumbersome.
Here's my initial approach:
export const throwIfUndefined = <T>(v: T | undefined): T => {
if (v === undefined) {
throw new Error("Unexpected undefined");
} else {
return v;
}
};
This method works in most cases:
const x = Math.random() < 0.5 ? undefined : 1;
throwIfUndefined(x); // works fine: type-checks correctly
throwIfUndefined(1); // issue: should trigger a type error because the input can never be undefined
How can I adjust it so TypeScript will flag unnecessary use of throwIfUndefined
?
I attempted using conditional types but couldn't wrap my head around how they would fit in this scenario.
Edit: Here's an example of code that I find tedious to write:
const item = array[index];
if (!item) return;
return item.function() ? 1 : 2;
The process becomes even more laborious when dealing with multiple elements in an array. I'd prefer a shortcut like this (eliminating the extra condition and variable declaration):
return throwIfUndefined(array[index]).function() ? 1 : 2