Replies: 1 comment 1 reply
-
So, there's several questions and answers around on this topic, including code snippets of people creating these types guards. However, it's important to understand that unfortunately a lot of them are wrong and some of them are unsafe 😅 In short, all of the properties you mention can be nullish, independent of each other.
In short, if you can ensure that these aren't the case, it's safe to leave the above cases out, however, as you can see, none of these are strictly guaranteed, and even tightening the types a little at the bindings level doesn't necessarily increase these guarantees. The safest way to handle this is to also ensure that |
Beta Was this translation helpful? Give feedback.
-
I created a simple todo app with GraphQL Code Generator. The code is quite similar to the one in the urql React tutorial.
Then, I got a following type error, because the type of
data
is notGetTodosQuery
butGetTodosQuery| undefined
I could solve it by adding a line which checks if
data
isundefined
.if (fetching) return <p>Loading...</p>; if (error) return <p>Oh no... {error.message}</p>; + if (!data) return <p>Something happens :(</p>; return ( <ul> {data.todos.map((todo) => ( <li key={todo.id}>{todo.title}</li> ))} </ul> );
I'm wondering if it can happen that all of
fetching
,error
anddata
are falsy. If not, I think we could clear this problem by updating the definition ofUseQueryState
.If we update
UseQueryState
as like the folliowing code, we can use type guards, which means we can assumedata
is notundefined
if bothfetching
anderror
are falsy without checkingdata
byif (!data) ...
. (I'm sorry that I'm not familiar with the use ofinterface
...)Maybe, some suggests me that we can write the following code to skip writing the annoying
if (!data) ...
. But with this code, we may be forget some behavior. For example, even if we forget to write{fetching&& ...}
, we can get no error but nothing displays while fetching.Anyway, no matter how, I really appreciate if we have type guard with
useQuery
:)references
reproduction: https://github.com/tnyo43/urql-request-type-guard/blob/a64238aa4375a645f45352eaf06bede1e7239011/src/Todo.tsx
Beta Was this translation helpful? Give feedback.
All reactions