typescript - 打字稿将所有日期从接口转换为字符串
问题描述
是否可以将所有Date
类型定义从我的接口转换为string
,因为它会自动转换为string
JSON stringify。
interface Item {
key: string;
value: number;
created: Date;
}
const item: Item = { key: 'abc', value: 1, created: Date() };
// convert to JSON
const itemJson = JSON.stringify(item);
// convert back itemJson to an object
const item2 = JSON.parse(itemJson);
// item2 is not of type `Item` as JSON.stringify convert Dates to strings
// so item2 is of type: { key: string; value: number; created: string; }
是否有一种功能可以将Date
类型从我的界面转换为string
? 就像是const item2: ToJSON<Item> = JSON.parse(itemJson);
注意:
我不想转换回item2.created
Date 但我想创建一个interface
对应于转换item
为item2
. 所以item
是不同的item2
,应该保持不同,因此我需要一个新的item2
. 当然,我可以手动完成,但我有一堆界面要转换,我想用类似于实用程序类型的东西来做这个:https ://www.typescriptlang.org/docs/handbook/utility-types .html
注意2:
目标是获得一个名为的新接口Item2
interface Item2 {
key: string;
value: number;
created: string;
}
类似的东西type Item2 = ToJSON<Item>
。
解决方案
TypeScript 类型系统 FTW:
interface Item {
key: string;
value: number;
created: Date;
}
type SwapDatesWithStrings<T> = {
[k in keyof(T)]: (T[k] extends Date ? string : T[k]);
}
type JsonItems = SwapDatesWithStrings<Item>;
// JsonItems is the same as:
// interface JsonItems {
// key: string;
// value: number;
// created: string;
// }
SwapDatesWithStrings
它可以从基本类型派生一个泛型类型T
,具有相同的一组属性T
,但在属性类型上有所不同:派生自 Date 的属性被转换为字符串。
推荐阅读
- javascript - Axios 未在请求中发送自定义标头(可能是 CORS 问题)
- qaf - QMetry:com.qmetry.qaf.automation.step.client.ScenarioFactory.getTestsFromFile() 抛出异常
- sql - 动态透视 3 列表
- dynamics-crm - Dynamics 自定义操作流程会话
- python - Pandas 'reduce' 和 'accumulate' 功能 - 不完整的实现
- c# - 浏览 Javascript 生成的网页
- javascript - 如何在js中用字符串进行大写?
- excel - 再次与嵌套循环 VBA 混淆
- ios - 根据json中的值进行搜索
- multithreading - Qt。如何正确打印来自 QThread 对象的数据?