Home > Back-end >  TS2322 when assigning cachelocation to localstorage in Typescript react auth0
TS2322 when assigning cachelocation to localstorage in Typescript react auth0

Time:02-06

I have the following code

const providerConfig = {
    domain: config.domain,
    clientId: config.clientId,
    onRedirectCallback,
    useRefreshTokens: true,
    // advancedOptions:{defaultScope: 'openid profile email offline_access'},
    cacheLocation: 'localstorage',
    authorizationParams: {
        redirect_uri: window.location.origin,
        ...(config.audience ? { audience: config.audience } : null),
    },
};


ReactDOM.render(
    <Auth0Provider  {...providerConfig}>
        <Root />
    </Auth0Provider>
    , document.getElementById('root')
);

Referencing this, trying to set cacheLocation to localstorage to I can use refresh tokens but I get this error:

Type '{ children: Element; domain: string; clientId: string; onRedirectCallback: (appState: any) => void; useRefreshTokens: boolean; cacheLocation: string; authorizationParams: { audience?: string; redirect_uri: string; }; }' is not assignable to type 'Auth0ProviderOptions'.
  Types of property 'cacheLocation' are incompatible.
    Type 'string' is not assignable to type '"localstorage" | "memory" | undefined'.  TS2322

After some research I find solutions for similar problems but not this in particular, some things I've tried were adding an exclamation after the string cacheLocation: 'localstorage'!, a question mark after cacheLocation so it would be cacheLocation?, using tilda's to surround the string instead of single quotes, and also double quotes, does anyone know how I can assign cacheLocation to localstorage here?

CodePudding user response:

The problem is that at cacheLocation: 'localstorage' Typescript stores it as type string and looses the information about the exact string content. If you mark it as readonly instead it will keep the precise type "localstorage" instead.

Therefore following works:

const providerConfig = {
    // ...
    cacheLocation: 'localstorage' as const, // <--- note the as const here
    // ...
};


ReactDOM.render(
    <Auth0Provider  {...providerConfig}>
        <Root />
    </Auth0Provider>
    , document.getElementById('root')
);
  • Related