[英]How do I work with TypeScript correctly when I need to change a type of a property in an object
I have this class that represents JSON incoming from POST request.我有这个类表示从 POST 请求传入的 JSON。
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.在我将它存储在我的 mongoDB 数据库中之前,我想将
expiredAt
的类型expiredAt
为Date
,所以我有另一个代表数据库模式的类。
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
expiredAt
可以为 null,我想创建一个对象来复制MilkCarton
类型的对象,但将其expiredAt
转换为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
.但是我碰到一个错误,因为
preparedMilk
已经推断出它的类型,并具有expiredAt
为string
,它不能变成Date
从打字稿角度来看,如果它的string
。 But I want it to turn into Date
, what is the approach to do that correctly in TypeScript?但我希望它变成
Date
,在 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.这有效,但并不完全是我所希望的,如果我有另一个示例,其中包含 3 个不同的深度嵌套 ISO
string
属性,需要转换为Date
(和向后),那么执行此解决方法将非常脏。
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?注意:我把类改成了接口,不知道这样行不行?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.