Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Define one prop as optional if another one is of specific enum type

Component prop type:

interface IRequireUserPermits {
  minimalRequiredRole: UserRoles;
  allowedPermissions: UserPermissions[];
}

UserRoles is an enum:

export enum UserRoles {
  SUPERADMIN = "SUPERADMIN",
  ADMIN = "ADMIN",
  AGENT = "AGENT",
}

How can I define allowedPermissions prop required only if the minimalRequiredRole prop is UserRoles.AGENT? Or the other way around – how to make prop optional only if the minimalRequiredRole prop is either UserRoles.SUPERADMIN or UserRoles.ADMIN?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

You are looking for discriminated unions. Instead of interface let’s use type for IRequireUserPermits:

type IRequireUserPermits =
  | {
      minimalRequiredRole: UserRoles.AGENT;
      allowedPermissions: UserPermissions[];
    }
  | {
      minimalRequiredRole: UserRoles.SUPERADMIN | UserRoles.ADMIN;
    };

Testing:

const case1: IRequireUserPermits = {
  minimalRequiredRole: UserRoles.AGENT,
  allowedPermissions: [], // no error
};

const case2: IRequireUserPermits = {
  minimalRequiredRole: UserRoles.ADMIN,
  allowedPermissions: [], // error
};

playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading