在分配之前使用的打字稿变量 [英] Typescript variable being used before assigned

查看:20
本文介绍了在分配之前使用的打字稿变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照说明遵循 此处,在构建我的 Apollo 客户端之前,我正在尝试从 Auth0 缓存我的端点 URL 和令牌:

As per instructions followed here, I'm trying to cache my endpoint URL and token from Auth0 before constructing my Apollo client:

import React from 'react';
import { ApolloClient, ApolloProvider, from, HttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/link-context';
import { useAuth0 } from './auth/AuthContext';

const App: React.FC = () => {
	const { isLoading, getTokenSilently, getIdTokenClaims } = useAuth0();

	if (isLoading) return <Loader />;

	let endpoint: string;
	let token: string;
	const contextLink = setContext(async () => {
		if (!token) {
			token = await getTokenSilently();
		}
		if (!endpoint) {
			endpoint = await getIdTokenClaims()['https://example.com/graphql_endpoint'];
		}

		return { endpoint, token };
	});

	/**
	 * TODO: check for autorization error and remove token from cache
	 * See: https://www.apollographql.com/docs/react/v3.0-beta/api/link/apollo-link-context/
	 */

	const apolloClient = new ApolloClient({
		cache: new InMemoryCache(),
		link: from([
			contextLink,
			new HttpLink({
				uri: endpoint || '',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${token}`
				}
			})
		])
	});

	return (
		<ApolloProvider client={apolloClient}>
			<div />
		</ApolloProvider>
	);
};

export default App;

我收到了上面 endpointtoken 的错误 TS2454(变量在分配之前使用).知道如何解决这个问题吗?

I'm getting the error TS2454 (variable is used before being assigned) for both endpoint and token above. Any idea how I can get around this?

推荐答案

您将 endpointtoken 声明为变量,但在检查之前未将它们初始化为任何内容它们在 setContext 中.

You're declaring both endpoint and token as variables, but not initializing them to anything before checking them inside of setContext.

    let endpoint: string;
    let token: string;
    const contextLink = setContext(async () => {
        if (!token) {
            token = await getTokenSilently();
        }
        if (!endpoint) {
            endpoint = await getIdTokenClaims()['https://example.com/graphql_endpoint'];
        }

        return { endpoint, token };
    });

尝试设置默认值:

let endpoint: string = "";
let token: string = "";

这篇关于在分配之前使用的打字稿变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆