Skip to content

How to easily access the type of the user returned from useAuth? #1121

@lx4r

Description

@lx4r

Sorry for diverging from the issue template but IMO this isn't a bug but more of a question.

I'm using the useAuth hook to log in users in a React + TS app. I then want to process the user object further before returning it from my custom hook:

export function useCustomAuth() {
    const { user: fronteggUser } = useAuth();

    function mapUser(user: /* Which type to use here? */) {
        // do something with the user
    }

    return {
        user: fronteggUser ? mapUser(fronteggUser) : null,
    };
}

My problem is that accessing the type of the user returned from useAuth is hard. I can't easily get the type from the return type of useAuth directly due to useAuth being overloaded and TS not being able to pick the correct overload in this case AFAIU:

// In this case the type of userFromFrontegg is `unknown` ...
function mapUser(
  userFromFrontegg: Exclude<ReturnType<typeof useAuth>, null | undefined>
) {
  // do something with the user
}

type HookReturnType = ReturnType<typeof useAuth>; // ... because this is `unknown`

type HookType = typeof useAuth; // ... because this is `{ (): AuthState; <S>(stateMapper: AuthStateMapper<S>): S; }`

I can get the type from a variable but this seems suboptimal:

const { user: fronteggUser } = useAuth();

function mapUser(
  userFromFrontegg: Exclude<typeof fronteggUser, null | undefined>
) {
  // do something with the user
}

My suggestion is to export the types AuthState, the return type of useAuth, and User from @frontegg/react to allow users to easily type the data returned by this hook. What do you think? Is there an easier way make this work maybe?

Thanks in advance for the help :)

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions