Is there a way to ensure that a function returns a value with the same type as the argument given to it, while still maintaining broader argument type restrictions than the original value?
For instance:
I need to trim a string value, but if the value is null
or undefined
, I want it to return the original null
or undefined
.
function trimOrOriginal(value?: string | null) {
return value ? value.trim() : value;
};
Let's say I have a non-optional field of type string | null
. If I try to trim this field and assign the trimmed value back to the original variable, I receive a compiler error because the trimOrOriginal
function can potentially return undefined
, even though the argument provided will never be undefined
.
I could utilize generics:
const trimOrOriginal = <T>(value: T) => {
if (typeof value === "string") {
return value.trim();
}
return value;
};
However, this approach isn't very clean. I would prefer to specify that the argument type must be specifically "string".