#Generics level up

12 messages · Page 1 of 1 (latest)

wary cave
#

I have this:

export function useAddAnonymousUserMutation(
    options?: UseMutationOptions<User>,
) {
    return useMutation<User>({
        ...options,
        mutationFn: () => addAnonymousUser(),
    })
}

so that when I call useAddAnonUserMut() I can add { onSuccess: => (data) => {} } and data can be of type User.

Thats all great, but I am wondering if there is a better way to write this.

I tried both

export function useAddAnonymousUserMutation<TData extends User>(
    options?: UseMutationOptions<TData>,
) {
    return useMutation<TData>({
        ...options,
        mutationFn: () => addAnonymousUser(),
    })
}

and

export function useAddAnonymousUserMutation<TData = User>(
    options?: UseMutationOptions<TData>,
) {
    return useMutation<TData>({
        ...options,
        mutationFn: () => addAnonymousUser(),
    })
}

and I get type errors that TData could be overridden by something with other type contstraints.

How would you make this code better/DRYer?

hoary tulip
#

In both of those, as far as I can tell, the issue is that addAnonymousUser returns a concrete type

#

whereas someone might call useAddAnonymousUserMutation with a type narrower than User

#

leading to inconsistent state and missing properties

#
declare function addAnonymousUser(): Promise<User> //not sure if this type is accurate

export function useAddAnonymousUserMutation<TData extends User>(
    options?: UseMutationOptions<User | TData>,
) {
    return useMutation<User | TData>({
        ...options,
        mutationFn: () => addAnonymousUser(),
    })
}

if you change useMutation to expect either just a bare User or a user with additional data, it'll all work

#

since addAnonymousUser is no longer constructing a potentially incompatible type.

#

afaik, anyway. I don't use react-query. If this doesn't work for you, please make a typescript playground demonstrating the issue with all of the involved types defined

wary cave
#

the type of addAnonUser is close,

function addAnonymousUser(): Promise<{
    id: string;
    isAnonymous: boolean;
} | null>
#

hm i see. maybe if null is gone, let me try

#

hm, even without the null, its the same error

#

ok ill close this. this seems to not be an issue with typescript, but with the types of the two libs i use, react-query and supabasejs

#

thank you very much though @hoary tulip!