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
You can map the keys of your
Thing
enum to be the new keys ofCanDos
with your nominated prefixYou 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