[英]How to type a function in TypeScript
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:直接执行 function 比通过注释为 function 的中间过程更有意义。但是 typescript 不像我那样思考并向我发出信号:
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'类型“void”不可分配给类型“ActionType”OptionsMenu.types.ts(10, 5):预期类型来自属性“action”,它在此处声明为类型“OptionsButtons”
Does anyone have a solution, please?请问有人有解决办法吗? :/
:/
You need to properly type the function您需要正确输入 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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.