如何为Executable数组推断所有execute方法首个参数的交集类型?
TypeScript泛型Executable数组的类型推断问题
基础接口定义
我有一组实现了泛型Executable接口的对象,基础类型定义如下:
interface Context {} interface Executable<TContext extends Context> { execute(context: TContext): void | Promise<void>; }
已实现的上下文交集类型工具
我已编写类型工具,用于推断数组中每个Executable的execute方法首个参数的交集:
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ( k: infer I ) => void ? I : never; type ContextUnion<TExecutables extends Executable<Context>[]> = TExecutables[number] extends Executable<infer TContext> ? TContext : never; type IntersectContextesOf<TExecutables extends Executable<Context>[]> = UnionToIntersection< ContextUnion<TExecutables> >;
类型推断正常的场景
不给数组steps标注类型时,context能被正确推断为两个execute上下文的交集,删除对应属性会触发TS错误:
interface RedContext { getRed(): string } const red = { async execute(context: RedContext) {} } interface BlueContext { getBlue(): string } const blue = { async execute(context: BlueContext) {} } const steps = [blue, red]; const context: IntersectContextesOf<typeof steps> = { getRed() { return 'red' }, // 注释以下行会触发预期的TS错误 // getBlue() { return 'blue' }, }
类型推断失效的场景
给steps标注Executable<Context>[]类型后,类型推断失效,删除属性不会触发错误:
const steps: Executable<Context>[] = [blue, red]; const context: IntersectContextesOf<typeof steps> = { getRed() { return 'red' }, // 不再触发TS错误 // getBlue() { return 'blue' }, }
最终需求与问题
我需要定义Operation接口,要求buildContext方法返回steps中所有execute上下文的交集,但当前写法下,注释getBlue不会触发TS错误,无法实现预期的类型校验:
interface Operation { buildContext(): IntersectContextesOf<typeof this['steps']>; steps: Executable<Context>[]; } const operation: Operation = { buildContext() { return { getRed() { return 'red' }, // 注释此行不会触发TS错误 // getBlue() { return 'blue' }, } }, steps: [blue, red], }
我需要解决该类型推断失效的问题,让buildContext的返回值能正确约束为steps中所有上下文的交集。
内容的提问来源于stack exchange,提问作者Bambou
相关产品推荐
相关产品推荐

