如何在Typescript中定义密钥回调对的类型



我有一个密钥回调对的对象作为

const entitiesUIEvents = {
newEntityButtonClick: () => {
history.push("/entity-management/entities/new");
},
openEditEntityDialog: (id) => {
history.push(`/entity-management/entities/${id}/edit`);
},
openDeleteEntityDialog: (id) => {
history.push(`/entity-management/entities/${id}/delete`);
},
openDeleteEntitysDialog: () => {
history.push(`/entity-management/entities/deleteEntitys`);
},
openFetchEntitysDialog: () => {
history.push(`/entity-management/entities/fetch`);
},
openUpdateEntitysStatusDialog: () => {
history.push("/entity-management/entities/updateStatus");
}
}

现在在另一个React函数中,我将这些回调作为传递

export function ActionsColumnFormatter(
cellContent:any,
row:Entity,
rowIndex:number,
{ openEditEntityDialog, openDeleteEntityDialog }  // Type Error here
) {
return (
<>
<a
title="Edit entity"
className="btn btn-icon btn-light btn-hover-primary btn-sm mx-3"
onClick={() => openEditEntityDialog(row.ipAddress)}
>
<span className="svg-icon svg-icon-md svg-icon-primary">
<SVG
src={toAbsoluteUrl("/media/svg/icons/Communication/Write.svg")}
/>
</span>
</a>
<> </>

<a
title="Delete entity"
className="btn btn-icon btn-light btn-hover-danger btn-sm"
onClick={() => openDeleteEntityDialog(row.ipAddress)}
>
<span className="svg-icon svg-icon-md svg-icon-danger">
<SVG src={toAbsoluteUrl("/media/svg/icons/General/Trash.svg")} />
</span>
</a>
</>
);
}

在上面的代码片段中,openEditEntityDialogopenDeleteEntityDialog具有任意类型。但我希望它们是打字安全的。请指导我怎么做。

您在回调中使用了析构函数语法。为析构函数参数指定显式类型很容易。

export function ActionsColumnFormatter(
cellContent:any,
row:number,
rowIndex:number,
{openDeleteEntityDialog, openEditEntityDialog}: {
openEditEntityDialog: (id: number) => void,
openDeleteEntityDialog: () => void,
}
): JSX.Element {
// ...
}

我还为ActionsColumnFormatter提供了显式的返回类型。

最新更新