首页 > 解决方案 > 打字稿将所有日期从接口转换为字符串

问题描述

是否可以将所有Date类型定义从我的接口转换为string,因为它会自动转换为stringJSON 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.createdDate 但我想创建一个interface对应于转换itemitem2. 所以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>

标签: typescripttypescript-typings

解决方案


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 的属性被转换为字符串。


推荐阅读