I am struggling with typing a simple function in Typescript that takes a union type and a boolean as parameters.
Here is the code snippet:
type A = 'a' | 'A';
function f(a: A, b: boolean): string {
if (b) {
switch (a) {
case 'a': return '';
case 'A': return '';
}
} else {
switch (a) {
case 'a': return '';
case 'A': return '';
}
}
}
When I enable strictNullChecks
, the compiler complains about a missing ending return statement and that the return type does not include 'undefined'.
I would rather avoid adding default cases to make sure all types in A
are handled correctly in f
. But, I can't figure out what branch I'm missing.
One solution I found was introducing an intermediate function like g
:
function g(a: A): string {
switch (a) {
case 'a': return '';
case 'A': return '';
}
}
function f2(a: A, b: boolean): string {
if (b) {
return g(a);
} else {
return g(a);
}
}
However, I prefer to compile f
without needing these extra functions. Any suggestions on how to achieve this?