Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Previous Type

Tags:

typescript

I've got a Product interface (with name, ...) and like to keep changes to these products with a Change interface. A Change is a Product and all properties of Product prefixed with the word previous.

Not that creating the type manually would be a big deal - but I feel like you can create a type for this. My current approach is something like:

type Previous<T> = T extends /* all properties of T prefixed with `previous` */

Any ideas?

like image 978
nehalist Avatar asked Mar 31 '26 20:03

nehalist


1 Answers

You can create such type by using template literal types, as referred in the Typescript docs.

The Previous type definition could look like this:

type Previous<Type> = {
    [Property in keyof Type as `previous${Capitalize<string & Property>}`]: Type[Property]
};

Then you could simply use this type like so:

interface Product {
    name: string;
    price: number;
}

type PreviousProduct = Previous<Product>;

Please note that the key remapping via "as" operator is working in TS version 4.1 and onwards.

like image 110
lukbrt Avatar answered Apr 02 '26 23:04

lukbrt



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!