#Getting type for component instead of standard convex db?

3 messages · Page 1 of 1 (latest)

surreal parcelBOT
#

Hi @brittle tusk. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on your code example, it looks like you're trying to create a type for a component that combines Convex database documents with some local state. Let me explain how to properly get types from your Convex schema.

Getting Types from Convex Schema

Convex provides several ways to get TypeScript types from your schema:

  1. Using the Doc type from the generated data model:
import { Doc } from "../convex/_generated/dataModel";

type Message = Doc<"messages">;

This is the recommended approach for most use cases as mentioned in the TypeScript documentation.

  1. If you need to use DataModelFromSchemaDefinition directly (which is what you're asking about), you can do so like this:
import { DataModelFromSchemaDefinition } from "convex/server";
import schema from "./schema"; // Your schema definition

type Message = DataModelFromSchemaDefinition<typeof schema>["messages"];

This approach is actually an internal type used in Convex code generation as noted in the server module documentation.

For Your Component

For your specific component case where you're combining streaming text with database results, you can define your type like this:

import { Doc } from "../convex/_generated/dataModel";

// Base type from your Convex schema
type MessageDoc = Doc<"messages">;

// Extended type for your component that includes in-progress messages
type Message = MessageDoc | {
  _id: string;
  text: string;
  message: {
    role: "assistant";
    content: string;
  };
};

You can also use other type helpers like WithoutSystemFields if you need to work with document types without the system fields:

#
import { WithoutSystemFields } from "convex/server";
import { Doc } from "../convex/_generated/dataModel";

type MessageWithoutSystemFields = WithoutSystemFields<Doc<"messages">>;

These approaches provide end-to-end type safety from your database schema to your React components, which is one of the key benefits of using Convex with TypeScript as described in End-to-end TypeScript with Convex.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: