I have a simple function like this
type TUndefinedIfEmpty<T> = T extends '' ? undefined : T;
/**
* If value is an empty string, Return undefined.
* Return value unchanged in all other cases.
*/
const undefinedIfEmpty = <T,>(value: T): TUndefinedIfEmpty<T> => {
if(typeof value === 'string' && value === '') {
return undefined;
}
return value;
}
In this case, typescript complains that
Type 'undefined' is not assignable to type 'TUndefinedIfEmpty<T>'
Why does this error out when the return type is specified?
I could just remove the return type and just work with the string | undefined types but I'm curious why that errors?