TypeScript映射类型自定义类回调返回联合类型问题求助
问题:自定义类型类与映射类型协作时回调导致联合类型展开的解决办法?
我希望让自定义类型类与TypeScript映射类型无缝协作,但使用回调时,结果会被展开为联合类型,这不是我想要的效果。具体看代码:
const any = (any?: any) => any; // CONSTRAINTS namespace Constraint { export type OBJ = { [K: string]: ANY }; export type OPT = ANY; // @ts-ignore // 我知道怎么修复这个,暂时忽略即可!谢谢 :) export type ANY = Str | Num | Obj<OBJ> | Opt<ANY>; } // TYPES type Nested<T extends { nested: unknown }> = T['nested']; type Opt<T extends Constraint.OPT> = OPT<T>; type Str = STR; type Num = NUM; type Obj<T extends Constraint.OBJ> = OBJ<T>; // CLASSES class OPT<T extends Constraint.OPT> { opt: undefined; constructor(public nested: T) {} } class OBJ<T extends Constraint.OBJ> { obj: undefined; public map<R extends Constraint.ANY>( cb: (value: Nested<this>[keyof Nested<this>]) => R ): Obj<{ [K in keyof Nested<this>]: R; }> { return any(cb); } constructor(public nested: T) {} } class STR { str: undefined; } class NUM { num: undefined; } // FUNCTIONS const Opt = <T extends Constraint.OPT>(nested: T): Opt<T> => new OPT<T>(nested); const Obj = <T extends Constraint.OBJ>(nested: T): Obj<T> => new OBJ<T>(nested); const Str = (): Str => new STR(); const Num = (): Num => new NUM(); // USE const example = Obj({ one: Str(), two: Num(), }); export const result = example.map((value) => Opt(value)); // => 看下面的类型结果
我得到的类型是:
Obj<{ one: Opt<STR | NUM>; two: Opt<STR | NUM>; }>
但我真正想要的是:
Obj<{ one: Opt<STR>; two: Opt<NUM>; }>
请问我是否需要使用HKTs(高阶类型),还是有其他解决方法?
内容的提问来源于stack exchange,提问作者Janek Eilts
相关产品推荐
相关产品推荐

