erquhart
erquhart8mo ago

Type predicate for Convex IDs?

Can I make a type predicate for convex ids
8 Replies
RJ
RJ8mo ago
I don't think so, because I think the point of a type predicate is to be able to use a runtime check to narrow the type of a value, but I don't believe there's any runtime distinction between a Convex Id and a string. I never use type predicates though, so I'm not 100% positive
erquhart
erquhartOP8mo ago
It's for runtime and type checking. But yeah, the runtime side has to actually be possible to make it work at all. I thought there was some kind of runtime check happening in convex when dealing with ids, but maybe not.
sshader
sshader8mo ago
I might not know what a type predicate is / what you're going for here, but here's probably the closest you can get (https://www.typescriptlang.org/play/?#code/C4TwDgpgBAkgJgHgCoD4oF4oGdgCcCWAdgOZQBkUA3lAPo3ACGARgDYQByDAthAFxRIoAXwBQIosAi4AZgwDG0ACINGTBlggAlCAzhSqIqFEIB7XFwYt8ALwjxkKABSq2nHvyQAaKPjj8cBCQAlPz2qFAAPsYAriwsIqIi0tGEcsD4JoQ+WPAAYrgmXEjMbMglHNwQTr78DIQg3i4V7gLlbhDecEz8yqrqWjp6uCE+cNmwiMWszVUGRrgQwNG4WV0AdKbmljZ2cM5tld6+QVAAhOiYhLHxQkA) We haven't really directly exposed the logic to check if a string seems like a valid Convex ID or a valid Convex ID for a certain table, so at the moment you need access to db
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
erquhart
erquhartOP8mo ago
that last function is exactly what I'm looking for, thank you! (id is Id<TableName> is the predicate)
RJ
RJ8mo ago
Right of course, that would work!
Hmza
Hmza8mo ago
i was doing 'as' instead 'is', didn't know 'is' a thing. GG
erquhart
erquhartOP8mo ago
as is for type assertions, which override the compiler and directly assert a type. is is for type predicates, which allow you to assert a type based on an arbitrary condition.
Hmza
Hmza8mo ago
i get it now

Did you find this page helpful?