I am having trouble understanding how I can implement generics in TypesScript. I know there are many similar questions but none seem to address my use case. (There is this question, but I have a different concern, namely that the output of the function is the same type as the input of the function)
I would like to have a function like this, where the generic is limited to two different types, and the output is the same type as the input:
const increase = <T extends string | number>(
param: T,
): T => {
if (typeof param === "number") {
// Here typescript should know that param can only be a number
return param + 1;
}
// Here TypeScript should know that param can only be a string
return "one more " + param;
};
const stringResult = increase("apple"); // "one more apple"
// Here TypeScript should know that stringResult is a string
const numResult = increase(2); // 3
// Here TypeScript should know that numResult is a number
However, this produces errors like the following:
Type 'number' is not assignable to type 'T'.
'number' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | number'.
But I did the type checking in the if statement above, ensuring that T should be a number and not a string | number.
Is what I'm desiring possible in TypeScript? And if so, what am I doing wrong?