首页 > 解决方案 > 如何正确标准化对象?

问题描述

我有User来自后端的对象的响应,其中包含属性birthday,它是typeof string,但我想将它转换为typeof Date(例如规范化数据)。

这是片段:

interface User {
  username: string
  birthday: Date
}

function normalizeUser(user: Omit<User, 'birthday'> & { birthday: string }): User {}

如何在打字稿中正确执行?

标签: typescript

解决方案


你可以这样做:

type Patch<T, Props> = Omit<T, keyof Props> & Props;

type User = {
    hello: string;
    whatever: number;
    birthdayReal: Date;
    birthdayPublic: Date;
}

declare function convertDate(s: string): Date;

function normalizeUser(user: Patch<User, { birthdayReal: string, birthdayPublic: string }>): User {
    const birthdayReal = convertDate(user.birthdayReal);
    const birthdayPublic = convertDate(user.birthdayPublic);
    const result: User = { ...user, birthdayReal, birthdayPublic };

    return result;
}

在 Playground 上查看此解决方案。

convertDate是一个任意函数,可以根据您的规则将字符串转换为日期 - 在您的真实代码中,它不应该是declared,而是必须实现。


推荐阅读