Currently, I am working on developing a function that is designed to return a specific value. In the event that the returned value is null or undefined, the function should then default to a pre-determined value.
function test<A, B>(input: A, fallbackValue: B): NonNullable<A> | B {
if (input == null || input == undefined) {
return fallbackValue;
} else {
return input;
}
}
However, upon testing this function, I encountered an error message that stated:
Type 'A' is not assignable to type 'B | NonNullable<A>'.
Type 'A' is not assignable to type 'NonNullable<A>'.
I find this puzzling because I have explicitly defined that NonNullable should be of type A without including null or undefined values in the function's logic. Am I missing something here?
For reference, you can view the code in the TypeScript playground here.