Crafting a Retro Style

I have an interface called Product which includes properties such as name, and I want to track changes to these products using a separate interface called Change. A Change should include the original Product as well as all of its properties prefixed with the word previous.

While manually creating this type is possible, I believe there may be a way to define a type for this. My current approach looks something like this:

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

Any suggestions?

Answer №1

To create a similar type, you can utilize template literal types as outlined in the Typescript documentation.

The following is an example of how the type definition might appear:

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

You can then use this type like this:

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

type PreviousProduct = Previous<Product>;

It's important to note that the key remapping with the "as" operator works in TypeScript version 4.1 and later.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to eliminate duplicate data from an HTTP response before presenting it on the client side?

Seeking assistance on how to filter out duplicate data. Currently receiving the following response: {username:'patrick',userid:'3636363',position:'employee'} {username:'patrick',userid:'3636363',position:&a ...

RxJS emits an array of strings with a one second interval between each emission

Currently, my code is set up to transform an Observable<string[]> into an Observable<string>, emitting the values one second apart from each other. It's like a message ticker on a website. Here's how it works at the moment: const ...

Exploring ways to display all filtered chips in Angular

As a new developer working on an existing codebase, my current task involves displaying all the chips inside a card when a specific chip is selected from the Chip List. However, I'm struggling to modify the code to achieve this functionality. Any help ...

Construct an outdated angular project from scratch

I'm facing an issue with an old Angular project that I'm trying to build. After pulling down the code, running npm install @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9f9095bccdd2cbd2c8">[email p ...

Exploring the intricacies of extracting nested JSON data in TypeScript

Can someone help me with this issue? https://example.com/2KFsR.png When I try to access addons, I only see [] but the web console indicates that addons are present. This is my JSON structure: https://example.com/5NGeD.png I attempted to use this code: ...

Is there a more efficient method for providing hooks to children in React when using TypeScript?

My component structure looks something like this: Modal ModalTitle ModalBody FormElements MySelect MyTextField MyCheckbox DisplayInfo ModalActions I have a state variable called formVars, and a function named handleAction, ...

Are there more efficient methods for locating a particular item within an array based on its name?

While I know that using a loop can achieve this functionality, I am curious if there is a built-in function that can provide the same outcome as my code below: const openExerciseListModal = (index:number) =>{ let selectedValue = selectedItems[index]; it ...

Utilize the npm module directly in your codebase

I am seeking guidance on how to import the source code from vue-form-generator in order to make some modifications. As a newcomer to Node and Javascript, I am feeling quite lost. Can someone assist me with the necessary steps? Since my Vue project utilize ...

Having difficulty utilizing defineProps in TypeScript

For some time now, I've been utilizing withDefaults and defineProps. Unfortunately, this setup has recently started failing, leaving me puzzled as to why! Here's a simple SFC example: <script setup lang = "ts"> const props ...

The search for d.ts declaration files in the project by 'typeRoots' fails

// Within tsconfig.json under "compilerOptions" "typeRoots": ["./@types", "./node_modules/@types"], // Define custom types for Express Request in {projectRoot}/@types/express/index.d.ts declare global { namespace Express { interface Request { ...

Converting a string to the Date class type in Angular 4: A comprehensive guide

Within my .ts file, I have a string that looks like this: const date = "5/03/2018"; I am looking to convert it into the default date format returned by Angular's Date class: Tue Apr 03 2018 20:20:12 GMT+0530 (India Standard Time) I attempted to do ...

Angular production application is experiencing issues due to a missing NPM package import

Objective I am aiming to distribute a TypeScript module augmentation of RxJS as an npm package for usage in Angular projects. Challenge While the package functions correctly in local development mode within an Angular application, it fails to import pro ...

Aggregating all elements in an array to generate a Paypal order

I'm currently working on a React project where I need to integrate the PayPal order function and include every item from an array. Below is my code snippet, but I'm struggling with how to achieve this: export default function Cart(): JSX.Element ...

What could be the reason behind TypeScript ignoring a variable's data type?

After declaring a typed variable to hold data fetched from a service, I encountered an issue where the returned data did not match the specified type of the variable. Surprisingly, the variable still accepted the mismatched data. My code snippet is as fol ...

Tips for streamlining a conditional statement with three parameters

Looking to streamline this function with binary inputs: export const handleStepCompletion = (userSave: number, concur: number, signature: number) => { if (userSave === 0 && concur === 0 && signature === 0) { return {complet ...

Enhance your AJAX calls with jQuery by confidently specifying the data type of successful responses using TypeScript

In our development process, we implement TypeScript for type hinting in our JavaScript code. Type hinting is utilized for Ajax calls as well to define the response data format within the success callback. This exemplifies how it could be structured: inter ...

Customizing a generic method in typescript

I am currently working on developing a base class called AbstractQuery, which will serve as a parent class to other classes that inherit from it. The goal is to override certain methods within the child classes. class AbstractQuery { public before< ...

Which TypeScript AsyncGenerator type returns a Promise?

I am currently in the process of assigning a return type to the function displayed below: async function *sleepyNumbers() { // trying to determine TypeScript type let n = 0; while (true) { yield new Promise(resolve => resolve(n++)); ...

Ways to implement the flow of change occurrences in the mat-select component

Seeking assistance with utilizing the optionSelectionChanges observable property within Angular Material's mat-select component. This property provides a combined stream of all child options' change events. I'm looking to retrieve the previ ...

Issue encountered when attempting to assign `fontWeight` within `makeStyles` using `theme` in Typescript: Error message states that the property is not

Currently, within my NextJS project and utilizing MUI, I am attempting to define a fontWeight property using the theme settings in the makeStyles function. Oddly enough, this issue only arises when building inside a docker container, as building locally po ...