I've tried to make a mapped type where I used set of Enums for keys and functions as values but I'm failing to get exact type when using that object.
View this as a very simplified version of my problem, I know I could make this work with if/else or switch statement but because of performance and clarity I wish to use sort of an dictionary as a data structure.
enum PossibleOperationEnum {
MULTIPLY = 'MULTIPLY',
LENGTH = 'LENGTH',
}
type MultiplyOperation = {
operation: PossibleOperationEnum.MULTIPLY;
element: number;
};
type StringLengthOperation = {
operation: PossibleOperationEnum.LENGTH;
element: string;
};
type AllOperations = MultiplyOperation | StringLengthOperation;
type ModificationFunction<T> = (
modification: Extract<AllOperations, { operation: T }>,
) => any;
// Simplified version (in the original I have a lot more keys/functions)
const config: { [k in PossibleOperationEnum]: ModificationFunction<k> } = {
LENGTH: (mod) => mod.element.length,
MULTIPLY: (mod) => mod.element * 2
};
const content: AllOperations[] = [
{
operation: PossibleOperationEnum.MULTIPLY,
element: 1,
},
{
operation: PossibleOperationEnum.LENGTH,
element: "test"
},
]
const contentList = content.map((mod) => {
return config[mod.operation](mod); // this is evaluating to never even tho this code works perfectly fine in practice.
})
Also typescript playground link: Playground