I have this class that represents JSON incoming from POST request.
class MilkCarton {
company: string;
price: number;
expiredAt?: string;
// ...20 more properties
}
Before I store it in my mongoDB database, I want to change the type of expiredAt to Date, so I have another class that represents the schema of the database.
class MilkCartonSchema: {
company: string;
price: number;
expiredAt?: Date;
// ...20 more properties
}
expiredAt can be null, I want to create an object that copies the object of type MilkCarton but has its expiredAt converted to Date
prepareMilkForDb(milk: MilkCarton): MilkCartonSchema {
const preparedMilk = {
...milk,
}
if (milk.expiredAt) {
preparedMilk.expiredAt = new Date(milk.expiredAt)
}
return preparedMilk;
}
But I run into an error because preparedMilk has already inferred its type and has expiredAt as string, it can't be turned into Date from TypeScript perspective if it's string. But I want it to turn into Date, what is the approach to do that correctly in TypeScript?
EDIT: I ended up going with:
prepareMilkForDb(milk: MilkCarton): MilkCartonSchema {
const preparedMilk = {
...milk,
...(milk.expiredAt && {
expiredAt: new Date(milk.expiredAt)
}),
}
return preparedMilk;
}
This works, but isn't exactly what I wished for, if I had another example with 3 different deep nested ISO string properties that need converting to Date (and backwards) it would be very dirty to do this workaround.
Does this work for you?
interface MilkCarton {
company: string;
price: number;
expiredAt?: string;
// ...20 more properties
}
interface MilkCartonSchema {
company: string;
price: number;
expiredAt?: Date;
// ...20 more properties
}
const prepareMilkForDb = (milk: MilkCarton): MilkCartonSchema => {
return {
...milk,
expiredAt: milk.expiredAt == null ? undefined : new Date(milk.expiredAt)
};
}
Note: I changed the classes to interface, I don't know if that's ok or not?