RJR
Convex Community3y ago
13 replies
RJ

Branded ID type constructor function

I like that IDs have been changed from classes to branded strings in 0.17, and I also like that they're treated as opaque (not constructable directly). But while upgrading, I just came across a situation in which I think it would make sense to be able to obtain an ID<"myTable"> from a
string
—when serializing the ID to the DOM, e.g. as the value attribute of a <select> element. The example in my code, snipped verbatim:

    <Select.Root
      value={filterByBrandPartnerId}
      onValueChange={(id) =>
        dispatch({
          _tag: "FilterByBrandPartnerChanged",
          filterByBrandPartnerId: id, // <-- id comes from the DOM as a string
        })
      }
    >


Perhaps it would be nice, for scenarios like these, to offer a function which tries to create a branded string by validating that the string is the correct format (length/content) for a Convex ID? I guess that would just mean validating that it's a UUID (v4). Something like:

import type { Id } from "~/convex/_generated/dataModel";

...

    <Select.Root
      value={filterByBrandPartnerId}
      onValueChange={(id) =>
        dispatch({
          _tag: "FilterByBrandPartnerChanged",
          filterByBrandPartnerId: Id.fromString<"brandPartners">(id)
        })
      }
    >


Of course I can coerce the string to the type I'd like, but this alternative could be nicer. Just a data point and a thought 🙂
Was this page helpful?