Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter Keys with Typescript Key Remapping (Removing Prefix)

The Typescript documentation has a section for "Key Remapping via as". Their example makes the object key longer, such as name becoming getName. This is that example:

type Getters<Type> = {
    [Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]
};

Is it possible to go in the reverse direction, removing the prefix instead of adding it?

type InputPerson = {
  getName: () => string
}

type ExpectedOutputPerson = {
  name: string
}
like image 414
Travis Watson Avatar asked Oct 29 '25 08:10

Travis Watson


1 Answers

Yes, you can use template literal types to parse string literal types as well as to concatenate them. You need to use conditional type inference with infer to do it by saying "does this string match "get" concatenated with something, and if so, what is that something?"

type UngetKey<K extends PropertyKey> =
    K extends `get${infer P}` ? Uncapitalize<P> : K

type Test1 = UngetKey<"getTestOne">;
// type Test1 = "testOne"

And now you can use it to build something that undoes your Getters<T>, with the proviso that you need to decide what to do when you get unexpected properties:

type Ungetters<T extends { [K in keyof T]:
    K extends `get${string}` ? () => any : never
}> = { [K in keyof T as UngetKey<K>]:
        ReturnType<T[K]>
    };

The type parameter T is constrained so that all members have to have keys starting with "get" and they have to be zero-arg methods:

type Oops = Ungetters<{ getAge(): number, oops: string }>; // error
// -----------------> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Types of property 'oops' are incompatible.

And then each property of the output is the return type of the corresponding input property, using the ReturnType<T> utility type:

type InputPerson = {
    getMyName: () => string;
    getAge: () => number;
}

type Output = Ungetters<InputPerson>;    
/* type Output = {
    name: string;
    age: number;
} */

Playground link to code

like image 190
jcalz Avatar answered Oct 31 '25 00:10

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!