When working with TypeScript, I have a function that takes a generic parameter with constraints:
function func1<U extends string>(param: U): U {
return param;
}
const result1 = func1('hello');
// The type of 'result1' is 'hello' -- Excellent!
Now, I want to enhance this function by allowing an optional additional type to be included in the return type. However, if I try to do so by providing a default parameter for the U type, TypeScript stops inferring the actual value of U and instead uses the supplied default type:
function func2<T = never, U extends string = string>(param: U): U | T {
return param;
}
const result2 = func2('hello');
// The type of 'result2' is 'hello' -- Great!
const result3 = func2<boolean>('hello');
// The type of 'result3' ends up being string | boolean -- Not desired, I want it to be 'hello' | boolean.
const result4 = func2<boolean, 'hello'>('hello');
// The type of 'result4' is 'hello' | boolean -- Correct but API seems redundant.
My query now is, Is there a way for TypeScript to continue inferring the type from the parameter? I am looking to avoid specifying a default type for U and always rely on TypeScript to infer that value. The following pseudo-code illustrates how I envision the complete API:
function func3<T = never, U extends string = infer>(param: U): U | T {
return param;
}
const result5 = func3('hello');
// The type of 'result5' would be 'hello' -- Perfect!
const result6 = func3<boolean>('hello');
// The type of 'result6' would be 'hello' | boolean -- Ideal!