DCsan
DCsan2y ago

Argument of type 'unknown' is not assignable to parameter of type 'Id<string>'.

The basic tutorials don't work with typescript. eg https://docs.convex.dev/functions/query-functions#query-arguments-and-responses when I try to make a query that takes params, in typescript, eg like this:
export const cards = query(async ({ db }, { id }) => {
return await db.get(id);
});
export const cards = query(async ({ db }, { id }) => {
return await db.get(id);
});
I get this error: Argument of type 'unknown' is not assignable to parameter of type 'Id<string>'. how do i pass params to a query in a way that compiles?
Queries | Convex Developer Hub
Queries are the bread and butter of your backend API. They fetch data from the
6 Replies
lee
lee2y ago
This error is similar to the typescript error Parameter 'id' implicitly has an 'any' type. -- it means your function argument is missing a type annotation. You can add the annotation like this:
export const cards = query(async ({ db }, { id }: { id: Id<"cards"> }) => {
return await db.get(id);
});
export const cards = query(async ({ db }, { id }: { id: Id<"cards"> }) => {
return await db.get(id);
});
lee
lee2y ago
There are more examples in the typescript docs https://docs.convex.dev/typescript and the Typescript demo https://github.com/get-convex/convex-demos/tree/main/typescript
TypeScript | Convex Developer Hub
Move faster with end-to-end type safety.
GitHub
convex-demos/typescript at main · get-convex/convex-demos
Demo apps built on Convex. Contribute to get-convex/convex-demos development by creating an account on GitHub.
erquhart
erquhart2y ago
Argument Validation | Convex Developer Hub
Argument validators ensure that queries,
DCsan
DCsanOP2y ago
thanks! for now i've been typing the query params
type QUser = {
id?: string;
};

// usercards join on basecards
export const get = query(async ({ db }, param: QUser) => {
const { id } = param;
const user = await db
.query("users")
.filter((q) => q.eq(q.field("id"), id))
.unique();

return user;
});
type QUser = {
id?: string;
};

// usercards join on basecards
export const get = query(async ({ db }, param: QUser) => {
const { id } = param;
const user = await db
.query("users")
.filter((q) => q.eq(q.field("id"), id))
.unique();

return user;
});
erquhart
erquhart2y ago
With validators:
export const get = query({
args: { id: v.optional(v.string()) },
handler: async ({ db }, { id }) => {
const user = await db
.query('users')
.filter((q) => q.eq(q.field('id'), id))
.unique()
return user
},
})
export const get = query({
args: { id: v.optional(v.string()) },
handler: async ({ db }, { id }) => {
const user = await db
.query('users')
.filter((q) => q.eq(q.field('id'), id))
.unique()
return user
},
})
Indy
Indy2y ago
Yep the using with validators is quite nice because it gives you both argument validation and types.

Did you find this page helpful?