|
| 1 | +import { useQuery } from "@tanstack/react-query"; |
| 2 | +import { Equal, Expect } from "../helpers/type-utils"; |
| 3 | + |
| 4 | +interface User { |
| 5 | + fullName: string; |
| 6 | + job: string; |
| 7 | +} |
| 8 | + |
| 9 | +const getUser = async (): Promise<User> => { |
| 10 | + return Promise.resolve({ |
| 11 | + fullName: "Matt Pocock", |
| 12 | + job: "Developer", |
| 13 | + }); |
| 14 | +}; |
| 15 | + |
| 16 | +/** |
| 17 | + * A bit of a hint to start with. useQuery has a LOT of overloads - but a lot |
| 18 | + * of them are disappearing in the next major version. The ones that'll be |
| 19 | + * sticking around are the first three. |
| 20 | + * |
| 21 | + * 1. How are the first three overloads different to the others? Put differently, |
| 22 | + * what's the thing that's similar about the first three that's different to |
| 23 | + * the other six? |
| 24 | + */ |
| 25 | + |
| 26 | +useQuery; |
| 27 | +// ^ CMD+click on this to see the overloads |
| 28 | + |
| 29 | +/** |
| 30 | + * 2. When you provide queryFn to useQuery, the type of query.data is inferred |
| 31 | + * as the return type of queryFn. Why is that? |
| 32 | + */ |
| 33 | +const query1 = useQuery({ |
| 34 | + queryFn: getUser, |
| 35 | +}); |
| 36 | + |
| 37 | +// Without initialData, the type of query1.data is User | undefined |
| 38 | +type test1 = Expect<Equal<typeof query1.data, User | undefined>>; |
| 39 | + |
| 40 | +/** |
| 41 | + * 3. When you provide initialData to useQuery, the type of query.data no longer |
| 42 | + * has undefined in it. Why is that? |
| 43 | + */ |
| 44 | +const query2 = useQuery({ |
| 45 | + queryFn: getUser, |
| 46 | + initialData: { |
| 47 | + fullName: "", |
| 48 | + job: "", |
| 49 | + }, |
| 50 | +}); |
| 51 | + |
| 52 | +// WITH initialData, the type of query.data is just User |
| 53 | +type test2 = Expect<Equal<typeof query2.data, User>>; |
0 commit comments