Have the following json structure, representing project: Projects[]:
[
{
"id": "345",
"permissions": {
"read": true,
"write": true,
"delete": false
}
},
{
"id": "123",
"permissions": {
"read": true,
"write": true,
"delete": false
}
}
]
What would be the best approach to define the object in Angular 12 / Typescript, in order to access the permissions of the projects?
I only want to define the permission names in one place (read, write, delete), hence I thought I would use an enum type.
Sample (not working):
export interface Project {
id: string;
permissions: permissions;
}
export type permissions = {
[key in permissionsEnum]: boolean;
}
export enum permissionsEnum {
read = "read",
write = "write",
delete = "delete"
}
Access of permission property via project ID:
hasProjectRead(projectId: string): boolean {
return !!this.projects.find((project => project.id === projectId && project.permissions[permissionsEnum.read] === true);
}
Error: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Permissions'.
If no fix for my approach makes sense, perhaps another approach is better in this case?
Thanks in advance
Apparently the solution was as simple as:
hasProjectRead(projectId: string): boolean {
return !!this.projects.find((project => project.id === projectId && project.permissions.read === true);
}