typescript - 如何正确标准化对象?
问题描述
我有User
来自后端的对象的响应,其中包含属性birthday
,它是typeof string
,但我想将它转换为typeof Date
(例如规范化数据)。
这是片段:
interface User {
username: string
birthday: Date
}
function normalizeUser(user: Omit<User, 'birthday'> & { birthday: string }): User {}
如何在打字稿中正确执行?
解决方案
你可以这样做:
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
是一个任意函数,可以根据您的规则将字符串转换为日期 - 在您的真实代码中,它不应该是declare
d,而是必须实现。
推荐阅读
- java - 蓝牙模块 JDY-08 找不到安卓设备
- arrays - React - 如何从数组 json 对象的数组中访问单个值
- asp.net-web-api - .Net 5 webAPI:使用自定义 ValidationAttribute 时的奇怪行为
- android - 如何在 Android Tv Leanback 库中隐藏 ListRow
- javascript - HERE Maps 是否支持在 REACT 中显示多条路线
- javascript - 使用 prerender cli 时,终端给出 TypeError: Cannot read property 'endsWith' of undefined
- docker - 运行 docker 文件后 curl 命令不起作用
- c++ - Parallel-hashmap:确定 C++ 版本
- shell - 尝试将命令存储在 shell 变量中,但它出错了
- javascript - JS 获取组件位置,既没有 GetElementById 也没有 getBoundingClientRect