refactor: enhance type definitions in dataModel.d.ts for improved type safety and clarity by integrating schema-based types

This commit is contained in:
Ben Allfree
2025-11-24 04:52:46 -08:00
parent 51d830ac31
commit 9cc1a96c1a
2 changed files with 32 additions and 16 deletions

View File

@@ -8,29 +8,29 @@
* @module
*/
import { AnyDataModel } from "convex/server";
import type {
DataModelFromSchemaDefinition,
DocumentByName,
TableNamesInDataModel,
SystemTableNames,
} from "convex/server";
import type { GenericId } from "convex/values";
/**
* No `schema.ts` file found!
*
* This generated code has permissive types like `Doc = any` because
* Convex doesn't know your schema. If you'd like more type safety, see
* https://docs.convex.dev/using/schemas for instructions on how to add a
* schema file.
*
* After you change a schema, rerun codegen with `npx convex dev`.
*/
import schema from "../schema.js";
/**
* The names of all of your Convex tables.
*/
export type TableNames = string;
export type TableNames = TableNamesInDataModel<DataModel>;
/**
* The type of a document stored in Convex.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Doc = any;
export type Doc<TableName extends TableNames> = DocumentByName<
DataModel,
TableName
>;
/**
* An identifier for a document in Convex.
@@ -42,8 +42,10 @@ export type Doc = any;
*
* IDs are just strings at runtime, but this type can be used to distinguish them from other
* strings when type checking.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Id<TableName extends TableNames = TableNames> =
export type Id<TableName extends TableNames | SystemTableNames> =
GenericId<TableName>;
/**
@@ -55,4 +57,4 @@ export type Id<TableName extends TableNames = TableNames> =
* This type is used to parameterize methods like `queryGeneric` and
* `mutationGeneric` to make them type-safe.
*/
export type DataModel = AnyDataModel;
export type DataModel = DataModelFromSchemaDefinition<typeof schema>;

14
convex/schema.ts Normal file
View File

@@ -0,0 +1,14 @@
import { authTables } from '@convex-dev/auth/server'
import { defineSchema } from 'convex/server'
const schema = defineSchema(
{
...authTables,
// your other tables...
},
{
strictTableNameTypes: false,
}
)
export default schema