Home > Software engineering >  Create Mapped Type but only change the type of uppercase keys
Create Mapped Type but only change the type of uppercase keys

Time:07-12

I'm trying to use type mapping to change the types on an object wrapped in a proxy - it more or less works but the mapping changes every key, and not just the uppercase ones, which would be ideal.

An example would be:

type Remapper<Type> {
  [P in keyof T]: DifferentType
}

I know there are conditional types but I can't seem to fathom how to say "Only if the key is in all uppercase" maybe something like :

type Remapper<Type> {
  [P in keyof T]: P === P.toUpperCase() ? DifferentType : T[P]
}

Obviously this doesn't work but that's effectively what I'm trying to do

CodePudding user response:

You can use the Uppercase utility type to test if a string extends its upper-cased version.

This example maps the values of all upper-case keys to false:

type Remapper<T> = {
  [P in keyof T]: P extends string ?
    P extends Uppercase<P> ? false : T[P] : T[P];
}

type Test = {
  lower: true;
  UPPER: true;
};

type Remapped = Remapper<Test>; /* = {
                                       lower: true;
                                       UPPER: false;
                                     } */
  • Related