skip to Main Content

I am trying to take an enum like this:

enum Thing {
  ValA = 'ValA',
  ValB = 'ValB',
  ValC = 'ValC'
}

and turn it into a type like this:

type CanDos = {
  CanValA: boolean;
  CanValB: boolean;
}

Basically just add "Can" to the front of all the enum keys so I can use it like this where the set of "Thing"s is arbitrary:

const result = checkIt([ Thing.ValA, Thing.ValB ]);
result.CanValA; // true | false
result.CanValB; // true | false
result.CanValC; // undefined

Is this possible?

2

Answers


  1. You can map the keys of your Thing enum to be the new keys of CanDos with your nominated prefix

    enum Thing {
      ValA = 'ValA',
      ValB = 'ValB'
    }
    
    type CanDos = {
      [K in keyof typeof Thing as K extends string ? `Can${K}` : never]: boolean 
    }
    

    screenshot of computed type

    Login or Signup to reply.
  2. You can use a template literal type to prefix the keys of a string enum, using the type utility Record<Keys, Type> like this:

    TS Playground

    enum Thing {
      ValA = "ValA",
      ValB = "ValB",
    }
    
    type CanDos = Record<`Can${keyof typeof Thing}`, boolean>;
       //^? type CanDos = { CanValA: boolean; CanValB: boolean; }
    
    

    Keep in mind that Thing as a type refers to a union of the values of the enum, and that Thing as a value refers to the enum object itself, so it’s necessary to refer to the type of the enum using typeof Thing in order to derive a union of its keys using the keyof operator.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search