[英]Convert specific types of values in an object to another type in TypeScript
Hi I want to declare a type from another type, eg嗨,我想从另一种类型声明一个类型,例如
// from this type
type Source = {
id: string
name: string
price: Decimal
createdAt: Date
}
// want to create this type
// Decimal and Date types are converted to string while other fields are kept untouched
type Destination = {
id: string
name: string
price: string
createdAt: string
}
// It is desired to declare the destination type with some generics:
type Destination = SomeGenerics<Source>;
Is it possible using TypeScript type manipulation ?是否可以使用TypeScript 类型操作?
Context: After JSON.stringify
an object and JSON.parse
, the fields with type Decimal or Date are converted into string.上下文:在
JSON.stringify
一个 object 和JSON.parse
之后,类型为 Decimal 或 Date 的字段被转换为字符串。 I want to create a type for the resulting object in the most effortless way, since there are many source types and declaring all the destination types by hand is hard to maintain.我想以最轻松的方式为生成的 object 创建一个类型,因为源类型很多,并且很难手动声明所有目标类型。
type JsonConverter<T extends Record<string, unknown>> = {[key in keyof T]: ToStringIfExtends<T[key], Date | Decimal>}
type ToStringIfExtends<K, E> = K extends E ? string : K
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.