简体   繁体   English

将 object 中的特定类型的值转换为 TypeScript 中的另一种类型

[英]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.

相关问题 如何将任何类型值的 object 转换为字符串值的 object (Typescript)? - How to convert object of any type values, to object of string values (Typescript)? TypeScript:在映射对象中推断特定类型的参数和函数的返回值 - TypeScript: Infer specific types of arguments and return values of functions in a mapped object “pick”函数的 TypeScript 泛型类型(结果对象值类型) - TypeScript generic type for "pick" function (result object values types) 用嵌套对象打字稿中的另一种类型替换特定类型 - Replace a specific type with another type in a nested object typescript Map Object Values to Another Object with Specific Model Typescript - Map Object Values to Another Object with Specific Model Typescript Typescript - 从类型数组转换为 Object 类型 - Typescript - Convert from Array of types to Object of types 如何在 Typescript 中用另一个对象的值派生一个对象类型? - How to derive an object type with another object's values in Typescript? 打字稿:限制对象值的类型 - Typescript: limiting types in object values 如何在 TypeScript 中将 TypeScript 对象类型转换为像 Object.values() 这样的联合类型? - How to convert TypeScript object type to union type like Object.values() in TypeScript? 将 object 值转换为 TypeScript 中的类枚举类型 - Convert object values to enum-like type in TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM