Skip to content

Add type inference from queryFn return type in query-db-collection #356

@KyleAMathews

Description

@KyleAMathews

Description

Currently, query-db-collection requires explicit type parameters or schema for type inference. This issue proposes adding support for inferring types from the queryFn return type, similar to how electric-db-collection uses its ResolveType system.

Current Behavior

Users must provide types in one of these ways:

// Explicit type parameter
const collection = createCollection<Todo>(queryCollectionOptions({...}))

// Schema inference
const collection = createCollection(queryCollectionOptions({ 
  schema: todoSchema,
  ...
}))

Proposed Enhancement

Add automatic type inference from queryFn when no explicit type or schema is provided:

// Type would be inferred from queryFn return type
const collection = createCollection(queryCollectionOptions({
  queryFn: async () => {
    const response = await fetch('/api/todos')
    return response.json() as Todo[] // Type inferred from here
  },
  ...
}))

Implementation Details

1. Create Type Helper

type InferQueryFnOutput<TQueryFn> = TQueryFn extends (
  context: QueryFunctionContext<any>
) => Promise<Array<infer TItem>>
  ? TItem
  : never

2. Add ResolveType System

type ResolveType<
  TExplicit = unknown,
  TSchema extends StandardSchemaV1 = never,
  TQueryFn = unknown,
> =
  unknown extends TExplicit
    ? [TSchema] extends [never]
      ? InferQueryFnOutput<TQueryFn> extends never
        ? Record<string, unknown> // fallback
        : InferQueryFnOutput<TQueryFn>
      : InferSchemaOutput<TSchema>
    : TExplicit

3. Update QueryCollectionConfig

Update the interface to use the new type resolution system, with priority:

  1. Explicit type (highest priority)
  2. Schema inference
  3. QueryFn return type inference
  4. Fallback to Record<string, unknown>

Benefits

  • Better developer experience with automatic type inference
  • Consistency with electric-db-collection's flexible type system
  • Reduces boilerplate when types are already defined in queryFn

Testing Requirements

  • Test type inference with various queryFn patterns
  • Ensure backward compatibility with existing usage
  • Verify priority order of type resolution

Related

  • Similar to electric-db-collection's ResolveType implementation in packages/electric-db-collection/src/electric.ts:47-57

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions