What is the best way to create a function that will return a duplicate of an object but with a modified data type for one of its properties?

My current objective with the code below:

Access playground here

interface SOME_OBJECT_DATE   { otherProp: boolean,  myDate: Date }
interface SOME_OBJECT_STRING { otherProp: boolean,  myDate: string }

function convertDateToString(obj: SOME_OBJECT_DATE): SOME_OBJECT_STRING {
    const newObj = {...obj} as SOME_OBJECT_STRING;
    newObj.myDate = obj.myDate.toJSON();
    return newObj;
}

The primary aim of this function is to change the type of the myDate property from Date to string. It also entails copying the remaining object properties, namely the otherProp property.

How can I modify the value of myDate, duplicate the obj parameter, and ensure the correct typing?

https://i.sstatic.net/V1VVy.png

This is the specific error message that I'm encountering:

https://i.sstatic.net/oDW5K.png

Please note: In my actual scenario, there are additional overloads (various types extending the "base" interface { myDate: Date }). Therefore, I have created a list of these overloads that will be utilized. However, I still need to ensure proper typing of the implementation, similar to the example provided above.

Answer №1

Creating an object of the desired type without using a wrongly-typed helper is simple.

If you are confident that you will fix the type mismatch later, you can temporarily employ a wrongly typed helper object and appease the compiler. However, in the scenario you provided, there is no need for such workarounds.

function convertDateToString(obj: SOME_OBJECT_DATE): SOME_OBJECT_STRING {
  return {
    ...obj,
   myDate: obj.myDate.toJSON()
  };
}

Link to Playground

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

Combining dynamic key types with other key types in typescript

Looking to create a dynamic key alongside other static key types in TypeScript. For example: { "organizationId": "NEW_ORG", "displayName": "Test Display", "photo": null, "1645661283562_tab": { ...

Zod combinator that accepts a dynamic field name

When converting XML to JSON, my library outputs {MyKey: T} for single-element lists and {MyKey: T[]} for multi-element lists. The equivalent TypeScript type is type XmlJsonArray<T, element extends string> = Record<element, T | T[]>. To implemen ...

Can I define a string to correspond to a property name in an interface using TypeScript?

I have the following interface as an example: interface Account { email: string; enabled: boolean; } I want to create a method that will return default values for the fields in this interface. This is what I have so far: function defaultValue(prop ...

Combining Several Middleware Functions in NextJs 13 for Authentication and Localization

Important Note If you are interested in exploring my code further, you can find the repository here. To access the specific code for the ott-platform, navigate to apps/ott-platform. Please make sure to create an account on Clerk and input your Clerk key i ...

Using Angular's ngFor directive to iterate over a collection based on a true

I am currently attempting to resolve the following condition: if the condition is true, display a button, otherwise hide the button. OfferMatching() { this.getmatchoffer.filter(obj => { debugger for (let i = 0; i < this.applicationJobList.length; i+ ...

Guide on accessing a File with Blob in Angular

Can you help me figure out why I am unable to send the input from my form and download a file at the same time? this.fg = this.fb.group({ rptReqCode:[''], rptCode:[''], parFldVal:[''], genType ...

Exploring the Power of Nested *ngFor in Angular 2

I am struggling with passing indexes to a function where the first parameter (ii) is coming back as undefined. <div *ngFor="let tab of screen.data.tabs; let indexTab = i;"> <div *ngIf="tab.active"> <div *ngIf="tab.questions"&g ...

Encountering unexpected compilation errors in an Angular 9 project while utilizing safe null accessing and null coalescing features?

It's really strange what happened with this project. It was working perfectly fine yesterday, and I even left 'ng serve' running after finishing my work without any issues. However, today when I tried to compile the app, I ran into problems ...

Passing variable values in Angular 6

Is there a way to transfer the value of a variable from Component1 to a variable in Component2 without using any template binding? I have two components, Header and Footer. In the Header component, there is a boolean variable called test that I need to pa ...

Encountering a Runtime Exception while setting up a Client Component in the latest version of Next JS (v13.3

I am facing an issue with a component in my Next JS website. When I attempt to convert it into a Client Component, the page fails to load in the browser and I encounter the following unhandled runtime exception: SyntaxError: "undefined" is not va ...

Variations in comparing tuple types in TypeScript

Exploring the TypeScript Challenge, there is a particular problem known as IsNever. The task at hand is to create a type called IsNever that takes input of type T. If the resolved type equates to never, the output should be true; otherwise, it should be fa ...

Publish the current namespace as a new module

Imagine I have a module where I define a namespace with various properties. Here's an example: declare module "database" { export namespace Database { namespace statics { type static1 = any; type static2 = any; } } const dat ...

Async function is improperly updating the array state by overwriting it completely instead of just updating one item as

I am working on a file upload feature where each uploaded file should have a progress bar that updates as the file gets uploaded. I'm using a state to keep track of selected files and their respective progress: interface IFiles { file: File; c ...

Limit the covariance of properties in generic arguments

When I define a generic argument of object type with specific mandatory properties (for example, in this function it requires the object to have timestamp: string), TypeScript allows for using a more specialized attribute type as a generic argument - as sh ...

Understanding how to leverage styles.module.scss for implementing personalized styling within react-big-calendar

I'm currently working with the react-big-calendar library in order to develop a customized calendar. However, I've encountered an issue where the SCSS styling is not being applied correctly. export const JobnsCalendar = () => ( <Calendar ...

What is the most effective way to transform values into different values using TypeScript?

If I have a list of country codes and I want to display the corresponding country names in my component, how can I achieve this using props? interface MyComponentProps { countryCode: 'en' | 'de' | 'fr'; } const MyComponent: ...

Using Typescript to define custom PopperComponent props in Material UI

I'm currently utilizing the Material UI autocomplete feature in my React and Typescript application. I'm looking to create a custom popper component to ensure that the popper is full-width. Here's how I can achieve this: const CustomPopper ...

Tips for resolving the TSLint error in Firestore related to the possibly undefined object

I've been working with Firestore using the code snippet provided in this link. However, I keep encountering an error that says Object is possibly 'undefined' when trying to access data.name. I'm confident that the document does contain ...

Is it possible to build a Node.js (Express) application using a combination of JavaScript and TypeScript?

Currently, I have a Node.js project (Express REST API) that is written in JavaScript. My team and I have made the decision to gradually rewrite the entire project into TypeScript. Is it possible to do this incrementally, part by part, while still being ab ...

Sorting by Date in JavaScript

My goal is to filter out the elements in an array that have a date (converted from string) greater than a specific date. _this.downloadData.forEach(_d => _d.LogTime = _d.LogTime.toString()); console.log(_this.downloadData.filter(x=>new Date(x.LogTi ...