Reputation: 31365
What I'm trying to accomplish with the following code:
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 (i.e: 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.
Upvotes: 0
Views: 53
Reputation: 25966
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()
};
}
Upvotes: 1