我正在redux存储中使用规范化的数据(所有复杂类型只是引用真实对象的id),我想使用Typescript的条件映射类型功能创建非规范化类型。
我保留了id所指对象的实际类型,因为它是通用参数,因此,如果仅使用非数组id属性,我就能正确地创建非规范化类型。
type Id<T extends HandlerBase<any>> = string & { __type: T };
class HandlerBase<T extends HandlerBase<T>> {};
class HandlerA extends HandlerBase<HandlerA> {
str: string;
b: Id<HandlerB>;
bArr: Id<HandlerB>[];
};
class HandlerB extends HandlerBase<HandlerA> {};
type DenormalizedHandler<T> = {
[P in keyof T]: T[P] extends Id<infer U> ? DenormalizedHandler<U> : T[P];
}
const handler: DenormalizedHandler<HandlerA> = undefined;
handler.str; // Is string
handler.b; // Is DenormalizedHandler<HandlerB>
handler.bArr; // Should be DenormalizedHandler<HandlerB>[]
现在,我需要弄清楚如何向DenormalizedHandler
添加第二个条件,以便它可以正确地将Id<U>
映射到DenormalizedHandler<U>
和Id<U>[]
映射到DenormalizedHandler<U>[]
。
答案 0 :(得分:1)
您只需要添加另一个条件,条件类型就可以像三元表达式一样嵌套:
type Id<T extends HandlerBase<any>> = string & { __type: T };
class HandlerBase<T extends HandlerBase<T>> {};
class HandlerA extends HandlerBase<HandlerA> {
str: string;
b: Id<HandlerB>;
bArr: Id<HandlerB>[];
};
class HandlerB extends HandlerBase<HandlerA> {};
type DenormalizedHandler<T> = {
[P in keyof T]:
T[P] extends Id<infer U> ? DenormalizedHandler<U> :
T[P] extends Array<Id<infer U>> ? Array<DenormalizedHandler<U>> :
T[P];
}
const handler: DenormalizedHandler<HandlerA> = undefined;
handler.str; // Is string
handler.b; // Is DenormalizedHandler<HandlerB>
handler.bArr; // Is DenormalizedHandler<HandlerB>[]