简体   繁体   中英

How to type a function that needs to return a copy of an object while also changing the type of one of its properties?

What I'm trying to accomplish with the following code:

Playground link

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 main goal of this function is to convert the type of the myDate property from Date to string . But I need to copy the rest of the object, ie: the otherProp property.

How can I update the myDate , copy the obj parameter and return the correct type?

在此处输入图片说明

This is the error I'm getting:

在此处输入图片说明

Note: In my real scenario, I have some other overloads (ie: I'll call it with multiple types that extends the "base" interface { myDate: Date } so I've made a list of overloads that I'll call it with, but I need to type the implementation, which should be something like the example above.

You can easily construct object of the desired type without a wrongly-typed helper.

Using a wrongly typed helper object and appeasing the compiler is a technique you may use if you know that you will correct the type to match its advertised interface, but in the example you posted there is no need to resort to these kind of tricks.

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

Playground link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM