inferring types from tRPC array

I'm trying to understand how to correctly work with inferring types when using a tRPC query, when i get an array of objects. Since i'm using prisma - i'm getting the types of the objects in the DB that i'm fetching, so my ucrrent solution is this; type Question = RouterOutputs["question"]["getAll"][0]; But this feels like a really bad solution/ work around. Furthermore - i'm getting the types as a prop from a different component upstream, with the current implementation. type Question = RouterOutputs["question"]["getAll"][0]; const Word: React.FC<{ question: Question }> = (props) => { if (!props.question) return <div>no data</div>; const question = props.question; return (........ Would appreciate some guidance as to what is the best practice here
7 Replies
isaac_way
isaac_way2y ago
What’s wrong with it? Probably what I would do, works pretty well because you don’t need intermediate types so refactoring and such can be faster. I think any other approach is more work to achieve more or less the same thing
splitfire?
splitfire?2y ago
i dont remember where I found it but I had a similar issue with the array element type thing and used this:
// Used to get elements of array types as types
type ArrElement<ArrType> = ArrType extends readonly (infer ElementType)[]
? ElementType
: never;
// Used to get elements of array types as types
type ArrElement<ArrType> = ArrType extends readonly (infer ElementType)[]
? ElementType
: never;
And then use it like this with trpc inferred types from routes:
type SubSectionUnitsFromServer =
RouterOutput["course"]["getSubSectionUnits"];

type SubSectionUnitItem = ArrElement<SubSectionUnitsFromServer>;
type SubSectionUnitsFromServer =
RouterOutput["course"]["getSubSectionUnits"];

type SubSectionUnitItem = ArrElement<SubSectionUnitsFromServer>;
im not sure if this is even ideal but ive been using it alot and it works
Christian Lind
Christian LindOP2y ago
It just feels like there should be a better way of defining the types than just grabbing the type of the first element in the list
isaac_way
isaac_way2y ago
Well the source of truth for your types is the return type of your endpoint’s resolver. Any solution that doesn’t get the type from there means you’re losing out on the free inference. If you use output schemas you can import the schema type into the front end. Just more work IMO but you might prefer it, and there are benefits to output schemas. Also if you don’t like the [0] you can do [number]
Christian Lind
Christian LindOP2y ago
Thanks for the help, still learning over here 🙂 - trying my best to avoid learning bad behaviors.
deforestor
deforestor2y ago
Sorry for reviving, but got an issue with this today Neither [0] nor [number] are a great solution because they still give me a typing error. This solution worked the best, thank you
isaac_way
isaac_way2y ago
🫡
Want results from more Discord servers?
Add your server