I am encountering an issue while trying to implement function overloading in TypeScript with an enum as a parameter and a second argument that depends on the enum's type.
Here is the breakdown:
- If the enum is
FOO
, the second argument should be of typestring
- If the enum is
BAR
, the second argument should be of typenumber
- If the enum is
BAZ
, there is no second argument required
Although I have the following code, TypeScript throws an error as even after checking the first argument against the enum, the type of the second argument is not narrowed down: fieldValue
is always string | number
.
enum ViewName {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
function myFunction(viewName: ViewName.FOO, stringValue: string);
function myFunction(viewName: ViewName.BAR, numberValue: number);
function myFunction(viewName: ViewName.BAZ);
function myFunction(viewName: ViewName, fieldValue?: string | number): void {
if (viewName === ViewName.FOO) {
fieldValue = fieldValue.reverse();
}
if (viewName === ViewName.BAR) {
fieldValue *= 2;
}
if (viewName === ViewName.BAZ) {
return console.log('No fieldvalue is supplied by BAZ.');
}
console.log(fieldValue);
}
You can also view the code on TypeScript Playground.