我在我的API中使用了用于RBAC(基于角色的访问控制)的Access Control NPM包。这是我的代码,用于检查用户是否拥有对资源的权限:
export const checkUserPermission = async (
req: Request,
role: string,
resource: string,
action = 'readAny'
) => {
const userRole = await Role.findOne({ name: role });
if (!userRole) return sendErrorResponse(res, 400, 'Role is not exists.');
const grantLists = await getPermissionsBasedOnRole(role);
if (grantLists.length === 0)
return sendErrorResponse(
res,
401,
'Permission is not assigned for this role. please assign and try again.'
);
const ac = new AccessControl(grantLists);
const permission = ac.can(role)[action](resource);
if (!permission.granted)
return sendErrorResponse(
res,
500,
'You have no permission to perform this action.'
);
};
在NodeJS中,该函数工作得很好。但当我尝试使用TypeScrip时,我得到了这样的错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Query'.
No index signature with a parameter of type 'string' was found on type 'Query'.
从…
const permission = ac.can(role)[action](resource);
1条答案
按热度按时间qpgpyjmq1#
在阅读了打字文档后,我找到了解决方案,特别是https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases
我只需使用TypeScrip中的类型别名声明操作的类型,并将操作类型注解为以下内容,一切都很正常:
以下是完整的源代码: