Home > front end >  Creating a Previous Type
Creating a Previous Type

Time:11-02

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?

CodePudding user response:

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.

  • Related