Noob TRPC quesiton regarding response JSON
I am struggling with parsing some JSON my TRPC API is responding, and hoping to receive some guidance.
I have a TRPC API which calls a table created in Prisma , as follows:
As you can see, it is being parsed as a
quiz
type, this is defined in prisma as follows:
Now, my problem is I want to access the properties of fetchedQuiz. specifcially, the quizData property. I know this JSON being returned has the properties questions
, "correctAns", "selectedAnswers" and "allAnswers". However typescript complains when I try to access these properties, because the JSON isnt defined in Prisma, giving me the error:
Property 'questions' does not exist on type 'string | number | boolean | JsonObject | JsonArray'
This is obviously because it can't parse the properties of the quizData Json from Prisma.
How would you suggest I go about ensuring this can be parsed?
Some things I have tried are:
Defining my own types for the response which matches the JSON, and then trying to cast the useQuery, as follows:
But this doesn't work, as fetchedQuiz
is still of type quiz.
Any suggestions are helpful.9 Replies
prisma is giving you the correct warning as a generic Json can have multiple types
on the query
you can "type" the result with no inference, allowing you to use
quizData
as the type that you wantHmmm I am not too sure I understand, I tried to do something like
But I don't understand why this wouldn't work?
as unknown as quizDataType
try this
This worked! I've never seen this done before but thank you.
you should not use if you can
what would the better practice be
the main issue is the Json type
as you cant know for sure the type
I see, so I suppose the optimal way would be to look into moving away from using Json in the schema
yeah