Skip to content

GramIO API Reference / @gramio/composer/dist / ContextOf

Type Alias: ContextOf<T>

ContextOf<T> = T extends object ? O : never

Defined in: composer/index.d.ts:377

Extracts the current accumulated context type (TOut) from an EventComposer or Composer instance type.

Use with a this: TThis parameter in custom methods to get automatic derive type inference — the handler receives all types from previous .derive() calls without requiring explicit annotation at the call site.

Type Parameters

Type Parameter
T

Example

ts
const { Composer } = createComposer({
  methods: {
    // Automatic: caller's derives are inferred into the handler
    command<TThis>(
      this: TThis,
      name: string,
      handler: Middleware<MessageCtx & ContextOf<TThis>>,
    ) {
      return (this as any).on("message", (ctx: any, next: any) => {
        if (ctx.text === `/${name}`) return handler(ctx, next);
        return next();
      }) as TThis;
    },

    // Manual: caller declares which derives they need via Patch generic
    hears<Patch extends object = {}>(
      trigger: string,
      handler: Middleware<MessageCtx & Patch>,
    ) {
      return this.on<"message", Patch>("message", (ctx, next) => {
        if (ctx.text === trigger) return handler(ctx, next);
        return next();
      });
    },
  },
});

// With ContextOf — no type annotation needed at call site:
new Composer()
  .derive(() => ({ user: { id: 1 } }))
  .command("start", (ctx) => ctx.user.id); // ✅ inferred automatically

// With Patch — caller declares what they need:
new Composer()
  .derive(() => ({ user: { id: 1 } }))
  .hears<{ user: { id: number } }>("hello", (ctx) => ctx.user.id); // ✅