【问题标题】:Typescript - how to retrieve keys of a generic type then build a new type from it? [duplicate]Typescript - 如何检索泛型类型的键然后从中构建新类型? [复制]
【发布时间】:2020-07-17 13:30:42
【问题描述】:

假设我们有这种类型:

type Product = {
  id: string;
  name: string;
  isActive: boolean;
  isAvailable: boolean;
}

是否可以从这个动态创建一个新类型,但键为snake_case,例如:

type ProductDb = {
  id: string;
  name: string;
  is_active: boolean;
  is_available: boolean;
}

事实上,我想定义一个对象 数据库映射器,如下所示:

class Mapper<Product, ProductDB> {
  ObjectToDb = (object: Product): ProductDb => {};
  DbToObject = (db: ProductDb): Product => {}
}

为了更进一步,拥有这个映射器的通用版本会很棒:

class Mapper<T, G> {
  ObjectToDb = (object: T): G => {};
  DbToObject = (db: G): T => {}
}

【问题讨论】:

标签: typescript


【解决方案1】:

评论链接有答案。如果您使用的是 TS 4.1+,您可以这样做:

type Product = {
    id: string;
    name: string;
    isActive: boolean;
    isAvailable: boolean;
};

type CamelToSnakeCase<S extends string> = string extends S
    ? string
    : S extends `${infer T}${infer U}`
    ? `${T extends Capitalize<T>
          ? '_'
          : ''}${Lowercase<T>}${CamelToSnakeCase<U>}`
    : S;

type ProductDb = { [K in keyof Product as CamelToSnakeCase<K>]: Product[K] };

生成的类型将如下所示:

type ProductDb = {
    id: string;
    name: string;
    is_active: boolean;
    is_available: boolean;
}

【讨论】:

    猜你喜欢
    • 2019-05-30
    • 2021-09-29
    • 2021-09-07
    • 1970-01-01
    • 2020-03-04
    • 2021-03-25
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    相关资源
    最近更新 更多