I am facing an issue where I have around 40 unique actions defined, all with the same parameters except for each being provided with a different schema which is causing the problem
type ActionName = 'replaceText' | 'replaceImage';
type ActionTypes = 'element';
interface Action {
objectId: string;
name: ActionName;
}
interface Params<S> {
element: {
action: Action & S;
}
}
const actions: Action[] = [{
name: 'replaceImage',
objectId: '123456'
}, {
name: 'replaceText',
objectId: 'replaceImage'
}];
class createAction<S, T extends ActionTypes> {
run(params: Params<S>[T]) {
console.log('paramas', params);
}
}
type ReplaceImageSchema = {
input: 'something'
}
type ReplaceTextSchema = {
input: 'somethingElse'
}
const internalActions = {
replaceImage: new createAction<ReplaceImageSchema, 'element'>(),
replaceText: new createAction<ReplaceTextSchema, 'element'>()
}
for (const action of actions) {
// the below fails because of conficting constituents
internalActions[action.name].run({
action
})
// the below works fine
switch (action.name) {
case 'replaceText': {
const params = { action } as Params<ReplaceTextSchema>['element'];
internalActions.replaceText.run(params)
}
break;
case 'replaceText': {
const params = { action } as Params<ReplaceImageSchema>['element'];
internalActions.replaceImage.run(params)
}
break;
}
}
Presently, I am using a switch statement with all available action names which is not ideal, hard to maintain, and involves repetitive code.
action.name
contains the correct type with a list of available action names as string literals. Params takes a single generic of type Schema
within the interface Schemas
Is there any way to solve this dynamically or is the switch statement the only solution?
It's important to mention that I have no control over which actions are available in actions
in the given example. They are sent via a service.