Reputation: 165
I have a list of objects with each an action field, I want to simplify this field of:
{
id: '2',
label: '',
text: () => translate('MapAnnotation.Circle'),
icon: 'circle',
action: () => {
optionsActionConstructor(MenuType.DRAW, GeometryType.CIRCLE);
},
}
to:
{
id: '2',
label: '',
text: () => translate('MapAnnotation.Circle'),
icon: 'circle',
action: optionsActionConstructor(MenuType.DRAW, GeometryType.CIRCLE);
}
So I did this :
type ActionType = (type?: MenuType, tool?: DrawGeometryType | OtherToolsType) => any;
export interface OptionsButtons {
id: string;
label: string;
text: () => string;
icon: AvailableIcons;
action: ActionType;
}
const optionsActionConstructor = (
type: MenuType.DRAW,
tool: DrawGeometryType | OtherToolsType,
): void => {
openedLeftMenuVar({ type, tool });
if (isAOtherToolsType(tool)) {
mapAnnotationsModalStatusVar({
open: true,
category: tool,
annotation: null,
});
}
if (isAGeometryType(tool)) {
drawAnnotationVar({
isActive: true,
geometryType: tool,
});
}
};
It makes more sense to execute the function directly rather than going through an intermediate annotated function. But typescript doesn’t think like me and signals me :
Type 'void' is not assignable to type 'ActionType' OptionsMenu.types.ts(10, 5): The expected type comes from property 'action' which is declared here on type 'OptionsButtons'
Does anyone have a solution, please ? :/
Upvotes: 0
Views: 147
Reputation: 1130
You need to properly type the function
type ActionType = (type?: MenuType, tool?: DrawGeometryType | OtherToolsType) => void;
const optionsActionConstructor: ActionType = (type, tool) => {
openedLeftMenuVar({ type, tool });
if (isAOtherToolsType(tool)) {
mapAnnotationsModalStatusVar({
open: true,
category: tool,
annotation: null,
});
}
if (isAGeometryType(tool)) {
drawAnnotationVar({
isActive: true,
geometryType: tool,
});
}
};
const item = {
id: '2',
label: '',
text: () => translate('MapAnnotation.Circle'),
icon: 'circle',
action: () => optionsActionConstructor(MenuType.DRAW, GeometryType.CIRCLE);
// the action field should contain a function, not a value. Moreover, the optionsActionConstructor function does not return anything.
}
Upvotes: 1