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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With