In my attempt to create a conditional-type function, I stumbled upon this question on Stack Overflow. Unfortunately, it seems that the approach doesn't work well with default values (regardless of where the default value is placed). Following the advice given there, I decided to use overloading instead.
Things seemed to be working fine...until I needed to call that function within a wrapper. Here's a simplified version:
// This part works:
// Conditional type function with default value
// as per https://stackoverflow.com/questions/57057697
type UnionType="one"|"two"|"three";
// function check(t?:"one"):1; // No impact
function check(t:"one"):1;
function check(t:"two"):2;
function check(t:"three"):3;
function check(t:UnionType="one") {
if(t=="one"){
return 1;
}else if(t=="two"){
return 2;
}else if(t=="three"){
return 3;
}
return 1;
}
// This causes an error:
// Invoking that conditional type function within another function,
// utilizing the same union type but only a single call
function check2(t:UnionType):1|2|3 {
return check(t);// <--- issue raised
}
// However, this one works:
// Calling that conditional type function within another function,
// using multiple identical calls (repetitive type checks)
function check3(t:UnionType):1|2|3 {
if(t=="one"){
return check(t);
}else if(t=="two"){
return check(t);
}else if(t=="three"){
return check(t);
}
return check(t);
}
The code does compile, but when viewed in the TypeScript playground, the compiler flags the check(t)
line in check2()
as not matching any overload. On the other hand, it has no issue with check3()
, even though both functions essentially perform the same task with redundant type checks.
Is this behavior intentional? What is the correct way to implement a conditional-type function with default values?