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 here7 Replies
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
i dont remember where I found it but I had a similar issue with the array element type thing and used this:
And then use it like this with trpc inferred types from routes:
im not sure if this is even ideal but ive been using it alot and it works
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
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]
Thanks for the help, still learning over here 🙂 - trying my best to avoid learning bad behaviors.
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
🫡