| undefined on tRPC procedures
This is a pretty noob question about typescript but a lot of the tRPC return types union a undefined type.
Is there a better way of dealing with this linting error besides casting it to the type or giving it a conditional back up like
28 Replies
can you send the function on your backend where this mutation is defined
i would need to change this then?
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
yea i noticed it was the prisma method findUnique that was unioning the undefined type, so changing it to findUniqueOrThrow and handling the error gives me the object without the undefined typing
Your input schema is defined as
string
so you must pass in a string
if what your trying to pass in is string | undefined
you need to handle the undefined case before you call the mutation
this is a bad place to cast, typescript is telling you things could go wrongah okay
also you might consider awaiting the prisma call before the return statement
you could never call the mutation at all, or
do something like this and let the backend throw the error when prisma doesnt find anything with a matching id
another question, do all trpc procedures union an undefined?
really the question is does prisma return possibly undefined
in hindsight this was actually wrong
it does not
as far as i know
in this case
findUnqiueOrThrow
will never be null, because prisma will throw if no matching item is found (what this means is the trpc query will error)
so the reason it is type | undefined
is because data is undefined when isError
is true
i thinkthis is helpful
also
i added a check for errors, but the type | undefined is still there
this isnt really a big problem but adding checks to all my props isnt very pretty
this is a weak point of typescript
it doesnt know that data + isError are connected
I would just add
probably a better solution out there
hmm it still is giving me an error since the types dont match up with the props types, which i can union an undefined to fix that
my mistake
i updated snippet
ah
interesting
thank you
np lmk if anything else comes up
bet tysm
so data will be undefined if its error or if the query is still loading
if you check for both of those cases data will stop being undefined i believe
(i havent tested with isLoading yet, but using
status==="loading"
and status==="error"
worked for me before, so i assume it will be the same)^ yup