Ale*_*dre 9 typescript typescript-typings
是否可以将所有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; }
Run Code Online (Sandbox Code Playgroud)
是否有一种功能可以将类型Date从我的界面转换为string?就像是const item2: ToJSON<Item> = JSON.parse(itemJson);
注意:
我不想转换回item2.createdDate,但我想创建一个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;
}
Run Code Online (Sandbox Code Playgroud)
就像是type Item2 = ToJSON<Item>。
A. *_*esa 16
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;
// }
Run Code Online (Sandbox Code Playgroud)
SwapDatesWithStrings它可以从基类型派生出通用类型T,具有与 相同的属性集T,但属性类型有所不同:从 Date 派生的属性将转换为字符串。
扩展@alberto-chiesa的答案,我们可以让它转换对象嵌套部分中的日期,并且也允许可选值:
export interface Item {
myDate: Date;
dateRange: {
start?: Date;
end: Date;
};
}
type NestedSwapDatesWithStrings<T> = {
[k in keyof T]: T[k] extends Date | undefined
? string
: T[k] extends object
? NestedSwapDatesWithStrings<T[k]>
: T[k];
};
type ItemWithStringDates = NestedSwapDatesWithStrings<Item>;
// Result:
// {
// myDate: string;
// dateRange: {
// start: string | undefined;
// end: string;
// };
// }
Run Code Online (Sandbox Code Playgroud)
它本质上是递归地尝试转换Dates为strings
| 归档时间: |
|
| 查看次数: |
2455 次 |
| 最近记录: |