[英]TypeScript - iterate over types in a dictionary type and create a type with transformed values
Note: This is not about runtime, we are talking purely about types here.注意:这不是关于运行时,我们在这里纯粹讨论类型。
Suppose there are types: Alpha<T>
, Beta<T>
and an example type like type Data = {a: Alpha<number>; b: Beta<string>, c: Alpha<string> }
假设有类型: Alpha<T>
, Beta<T>
和一个示例类型,例如type Data = {a: Alpha<number>; b: Beta<string>, c: Alpha<string> }
type Data = {a: Alpha<number>; b: Beta<string>, c: Alpha<string> }
I need to transform it to something like: {a: number; b: string; c: string }
type Data = {a: Alpha<number>; b: Beta<string>, c: Alpha<string> }
我需要将其转换为: {a: number; b: string; c: string }
{a: number; b: string; c: string }
I know how to transform a single value, I have this implemented already, but I have no idea how could I iterate over a dictionary type with known properties and transform them.我知道如何转换单个值,我已经实现了,但我不知道如何迭代具有已知属性的字典类型并转换它们。 Is it even possible?甚至可能吗?
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 }
One thing to note is that the 2 classes are known, but Data
in the real case is a generic.需要注意的一点是这 2 个类是已知的,但实际情况下的Data
是通用的。 It has a finite amount of properties, but it's all dynamic.它具有有限数量的属性,但都是动态的。 Manually applying the transformations is out of question.手动应用转换是不可能的。
Ah, you're just looking for a mapped type :啊,您只是在寻找映射类型:
type GetStoreData<T extends Store> = {
[K in keyof T]: GetClassParameterForAlphaBeta<T[K]>
}
You can verify that it works as expected:您可以验证它是否按预期工作:
type X = GetStoreData<Data>
/* type X = {
a: number;
b: string;
c: string;
} */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.