![](/img/trans.png)
[英]How to convert object of any type values, to object of string values (Typescript)?
[英]Convert specific types of values in an object to another type in TypeScript
嗨,我想從另一種類型聲明一個類型,例如
// 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>;
是否可以使用TypeScript 類型操作?
上下文:在JSON.stringify
一個 object 和JSON.parse
之后,類型為 Decimal 或 Date 的字段被轉換為字符串。 我想以最輕松的方式為生成的 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.