【问题标题】:TypeScript - iterate over types in a dictionary type and create a type with transformed valuesTypeScript - 遍历字典类型中的类型并创建具有转换值的类型
【发布时间】:2021-07-11 16:13:07
【问题描述】:

注意:这不是关于运行时,我们在这里纯粹讨论类型。

假设有类型:Alpha<T>Beta<T> 和像 type Data = {a: Alpha<number>; b: Beta<string>, c: Alpha<string> } 这样的示例类型,我需要将其转换为类似:{a: number; b: string; c: string }

我知道如何转换单个值,我已经实现了,但我不知道如何迭代具有已知属性的字典类型并转换它们。有没有可能?

class Alpha<T> {
    private a: T;
}

class Beta<T> {
    private b: T;
}

// Extracts T from Alpha<T> or Beta<T> - already implemented
type GetClassParameterForAlphaBeta<T extends Alpha<any> | Beta<any>> =
    T extends Alpha<infer R>
    ? R : T extends Beta<infer R>
    ? R : unknown;

type Store = { [index: string]: Alpha<any> | Beta<any> }

// pseudo-code to give you an idea of what I'm after
type GetStoreData<T extends Store> = T each U : GetClassParameterForAlphaBeta<U>;

type Data = {a: Alpha<number>; b: Beta<string>, c: Alpha<string> }

type x = GetStoreData<Data> // Expected: {a: number; b: string, c: string }

需要注意的是,这 2 个类是已知的,但实际情况下的 Data 是一个泛型。它具有有限数量的属性,但都是动态的。手动应用转换是不可能的。

【问题讨论】:

    标签: javascript typescript typescript-typings typescript-generics


    【解决方案1】:

    啊,你只是在寻找mapped type

    type GetStoreData<T extends Store> = {
      [K in keyof T]: GetClassParameterForAlphaBeta<T[K]>
    }
    

    您可以验证它是否按预期工作:

    type X = GetStoreData<Data> 
    /* type X = {
        a: number;
        b: string;
        c: string;
    } */
    

    Playground link to code

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 2021-08-29
      • 2015-08-26
      • 1970-01-01
      • 2019-10-14
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多