I'm running into a little issue when trying to implement function overloading with TypeScript in conjunction with an enum being passed as a parameter, and a second argument whose type depends on the enum.
For example:
- If the enum is
FOO, then the second argument is of astringtype - If the enum is
BAR, then the second argument is of anumbertype - If the enum is
BAZ, there is no second argument
The code I have is as follow, but somehow TypeScript throws an error because even when I'm checking the first argument against the enum, intellisense does not narrow down the type of the second argument: 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);
}
The code can also be viewed on TypeScript Playground.