Bird
0
0

Given this guard code, what will canActivate return when the user role is 'admin'?

medium📝 component behavior Q4 of 15
NestJS - Guards
Given this guard code, what will canActivate return when the user role is 'admin'?
class RoleGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return request.user?.role === 'admin';
  }
}
AAlways true
Btrue if user role is 'admin', false otherwise
CAlways false
DThrows an error if user is undefined
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the return condition

    The method returns true only if request.user?.role equals 'admin'.
  2. Step 2: Understand optional chaining effect

    If user is undefined, optional chaining returns undefined, so the comparison is false.
  3. Final Answer:

    Returns true if role is 'admin', else false -> Option B
  4. Quick Check:

    Role check returns true only for 'admin' [OK]
Quick Trick: Optional chaining prevents errors if user is missing [OK]
Common Mistakes:
  • Assuming always true
  • Assuming always false
  • Expecting error when user is undefined

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes