Home > Net >  Extract type using boolean field and conditional type from constant
Extract type using boolean field and conditional type from constant

Time:04-28

I have a constant that I'm trying to extract a type from:

const PERMISSIONS = {
   viewer: {
     category: 'View',
     label: 'View Access Only',
     deprecated: true
   },
   full_user: {
     category: 'Edit',
     label: 'Full Access',
     deprecated: false
   },
   admin: {
     category: 'Edit',
     label: 'Admin Access',
     deprecated: false
   }

} as const;

I am able to extract a category|label string type using this:

type RoleToPermissionsMap = typeof PERMISSIONS
type keys = keyof RoleToPermissionsMap;
type values = RoleToPermissionsMap[keys];
type categories = `${values['category']}`;
type labels = `${values['label']}`;
type magickeys = `${categories}|${labels}` 
// 'View|View Access Only' | 'View|Full Access' | 'View|Admin Access' | 'Edit|View Access Only' | 'Edit|Full Access' | 'Edit|Admin Access';
type filteredMagicKeys = ? // Not sure how to filter out 'deprecated: false'

My desired type filters out based on the deprecated flag. So in this example it would only have the 'Edit|*' strings.

I believe everything I'm looking for is available at compile time, so I should be able to express this type, but I don't know how to filter the constant based on the deprecated flag.

CodePudding user response:

When extracting the value, add in an Exclude so that if { deprecated: true } is assignable, the object gets excluded from the union.

type RoleToPermissionsMap = typeof PERMISSIONS;
type values = Exclude<RoleToPermissionsMap[keyof RoleToPermissionsMap], { deprecated: true }>;
type filteredMagicKeys = `${values['category']}|${values['label']}`;
  • Related