You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 04:34:59