I want to make a function that receives string | undefined and also returns string | undefined. This was my first approach:
sanitizeName: (name: string | undefined): string | undefined => {
return name?.replace(...)
},
However, when I call this function with a string argument, I know for sure it will also return a string, but now the type is string | undefined and I need an extra existence check.
What I tried is assigning a generic T that is string | undefined, and it is the parameter and returned type:
sanitizeName: <T extends string | undefined>(name: T): T => {
return name?.replace(...)
},
In my head, this should work: if the function receives undefined, it returns undefined. If it receives a string, it returns a string.
But I got this error:
Type 'string | undefined' is not assignable to type 'T'.
'string | undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | undefined'.
Type 'undefined' is not assignable to type 'T'.
'undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | undefined'.ts(2322)
Why is that? How can I get the desired behavior (string returns string, undefined returns undefined)?
>Solution :
I had to build a similar function, it seems like typescript cannot infer the subtype of T this way, so I had to do something like this:
function sanitizeName(name: string): string;
function sanitizeName(name: undefined): undefined;
function sanitizeName(name: string | undefined): string | undefined {
return ...
}
Learn more here about Function Overloads