【发布时间】:2021-06-19 11:18:00
【问题描述】:
我正在尝试以递归方式将日期字符串格式化为日期对象,但出现错误:
type JsonBody<T> = T extends Date
? string
: T extends (infer U)[]
? JsonBody<U>[]
: T extends object
? { [P in keyof T]: JsonBody<T[P]> }
: T;
type Person = {
name: string;
friend?: Person;
createdAt: Date;
};
type PersonWithFriend = Omit<Person, "friend"> & Required<Pick<Person, "friend">>;
function formatPerson<T extends Person>(body: JsonBody<T>): T {
return {
...body,
friend: body.friend && formatPerson(body.friend),
createdAt: new Date(body.createdAt)
};
// Type 'JsonBody<T> & { friend: Person | undefined; createdAt: Date; }' is not assignable to type 'T'.
// 'JsonBody<T> & { friend: Person | undefined; createdAt: Date; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Person'.
}
const one: JsonBody<Person> = { name: 'One', createdAt: '2021-01-21 00:59:11.07+00' };
const two: JsonBody<PersonWithFriend> = { name: 'One', friend: { name: 'Two', createdAt: '2021-01-21 00:59:11.07+00' }, createdAt: '2021-01-21 00:59:11.07+00' };
const oneFormatted = formatPerson(one).createdAt; // should be Date
const twoFormatted = formatPerson(two).friend.createdAt; // should be Date
为什么formatPerson(JsonBody<T extend Person>) 不返回T 以及为什么T 不变成Person 或PersonWithFriend,这取决于传递的参数?
提前感谢您的帮助。
【问题讨论】:
-
您应该将
..body编辑为...body -
糟糕,感谢您的提醒。我修复了它并更新了错误和游乐场。
标签: typescript