#is v.id() supposed to be typed?

4 messages · Page 1 of 1 (latest)

maiden crag
#

import { Infer, v } from 'convex/values';
import { QueryCtx } from '../../../_generated/server';

const GetUserCollectionQueryArgs = v.object({
userId: v.id('user'),
collectionId: v.id('bob'),
});

export const getUserCollectionHandler = async (
ctx: QueryCtx,
args: Infer<typeof GetUserCollectionQueryArgs>
) => {};

v.id('bob') is not a table, and im not getting any table types when using v.id

covert orchidBOT
#

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

#

Yes, v.id("tableName") is supposed to be typed in TypeScript. When you use v.id("user"), it creates a validator for an ID belonging to the "user" table, and the inferred type for that field will be Id<"user">. This is how Convex provides end-to-end type safety for document IDs, ensuring that only IDs from the correct table are accepted in your function arguments and schemas.

However, if you use a string like "bob" that does not correspond to a defined table in your schema, TypeScript will not be able to infer a specific type for Id<"bob">—it will still create a branded type, but it won't be connected to any actual table unless "bob" exists in your schema. The type system does not check at compile time whether the table name you pass to v.id() is a real table; it just creates a branded type for whatever string you provide. The runtime validator will expect an ID string formatted for that table, but it won't know if the table actually exists unless you have a schema defined for it.

If you are not seeing any table types when using v.id, it may be because your schema does not define those tables, or you are not importing the generated types correctly. When you define a schema, Convex generates types like Id<"user"> and Doc<"user"> for you to use throughout your codebase, ensuring type safety (Types Cookbook).

#

Key points:

  • v.id("tableName") is typed as Id<"tableName">.
  • If "bob" is not a table in your schema, Id<"bob"> is still a valid type, but it won't correspond to any real table unless you define it.
  • TypeScript will not error at compile time for using a non-existent table name, but your code may not work as expected at runtime if the table doesn't exist.
  • Make sure your schema is defined and types are generated for proper type inference (Stack: End-to-end TypeScript).

For more details, see the Convex documentation on validators and document IDs.

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