Skip to content

[FEATURE] RuntimeContext supports more accurate type definition #4467

@zero0-1one

Description

@zero0-1one

Problem Statement

The type definition of RuntimeContext is type-safe and accurate when set(). However, it is safe but inaccurate when get(), which is very inconvenient to use.
For example:

type MyRuntimeContext = {
  name: string;
  age: number;
};

const runtimeContext = new RuntimeContext<MyRuntimeContext>();
runtimeContext.set('name', 'John');
runtimeContext.set('age', 20);

// The following get('age') infers string|number, but expects number
const age = runtimeContext.get('age');

Proposed Solution

The following is the type redeclare I used in the project:

declare module '@mastra/core/runtime-context' {
  export class RuntimeContext<Values extends Record<string, any> = Record<string, any>> {
    private registry: Map<string, any>;
    constructor(iterable?: Iterable<{ [K in keyof Values]: [K, Values[K]] }[keyof Values]>);
    set<K extends keyof Values>(key: K, value: Values[K]): void;
    set(key: string, value: unknown): void;
    get<K extends keyof Values>(key: K): Values[K];
    get(key: string): unknown;
    has(key: string): boolean;
    delete(key: string): boolean;
    clear(): void;
    keys(): IterableIterator<keyof Values>;
    values(): IterableIterator<Values[keyof Values]>;
    entries(): IterableIterator<{ [K in keyof Values]: [K, Values[K]] }[keyof Values]>;
    forEach<K extends keyof Values>(callbackfn: (value: Values[K], key: K, map: Map<string, any>) => void): void;
    size(): number;
  }
}

Component

Workflows

Alternatives Considered

No response

Example Use Case

for (const [key, value] of runtimeContext.entries()) {
  if (key === 'age') {
    // value is correctly inferred as number
  } else {
    // value is correctly inferred as string
  }
}

Additional Context

No response

Verification

  • I have searched the existing issues to make sure this is not a duplicate
  • I have provided sufficient context for the team to understand the request

Metadata

Metadata

Assignees

No one assigned

    Labels

    Runtime ContextIssues surrounding Mastra's Runtime Context featureenhancementNew feature or requesthelp wantedMaintainers would appreciate community help on this.impact:mediump: lowLow priority

    Projects

    Status

    Ready

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions