I have created a function that takes a string name and a varying number of parameters which should be inferred from a specific interface. While calling this function results in correct inference, the type is not narrowed down within the function itself.
interface ThingParams {
A: [isThing: boolean];
B: [thingCount: number];
}
function PerformAction<T extends keyof ThingParams>( actionName: T, ...parameters: ThingParams[T] )
{
if ( actionName === 'A' )
{
// Why is foo typed as boolean | number instead of being correctly inferred to just boolean???
const foo = parameters[0]
}
}
PerformAction( 'A', true ); // Correctly limits possible values
PerformAction( 'B', 5 ); // No issues
PerformAction( 'B', false ); // Receives errors, as expected
It appears that the type of foo
should be narrowed based on the condition involving a specific T
. I'm looking for a solution without expanding types excessively like
interface ActionA { name: 'A', value: [isThing: boolean] }
interface ActionB { name: 'B', ... }
type ActionParams = ActionA | ActionB;
...
when all I require is a straightforward mapping. Is there a better approach in defining PerformAction
to accurately narrow down types within its implementation?