DEV Community

Discussion on: TypeScript 'instanceof' interface is it possible?

Collapse
kostyatretyak profile image
Костя Третяк

Try this:

const enum Permission {
  canRead = 1,
  canWrite = 2
}

class User {
  constructor(public permissions: Permission[] = []) {}
}

function guardAccess(user: User) {
  if (!user.permissions.includes(Permission.canWrite)) {
    throw new AccessDeniedException();
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
worldpwn profile image
Andrei Kniazev Author

This article is not about specific domain but about how to check interface at runtime.

And proposed solution works if you don’t need polymorphism.
For example you have role reader that can only read and role writer with claims for what it can write.