javascript 在Typescript react auth0中将缓存位置分配给本地存储时出现TS2322

tv6aics1  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(97)

我有下面的代码

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')
);

引用此命令,尝试将cacheLocation设置为localstorage,我可以使用刷新令牌,但出现以下错误:

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

经过一些研究,我找到了类似问题的解决方案,但不是特别的,我尝试过的一些事情是在字符串cacheLocation: 'localstorage'!,后添加一个感叹号,在cacheLocation后添加一个问号,这样它就变成了cacheLocation?,使用tilda的来包围字符串,而不是单引号,还有双引号,有人知道我如何在这里将cacheLocation赋值给localstorage吗?

ibrsph3r

ibrsph3r1#

问题是在cacheLocation: 'localstorage'时,Typescript将其存储为类型string,并丢失了有关字符串确切内容的信息,如果将其标记为只读,它将保留精确类型"localstorage"
因此,开展了以下工作:

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

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

相关问题