Typescript 类型脚本中的Apollo客户端返回类型

Typescript 类型脚本中的Apollo客户端返回类型,typescript,apollo,react-apollo,apollo-client,Typescript,Apollo,React Apollo,Apollo Client,我试图在返回Apollo客户端的类中构建一个简单的函数。这是我的密码: import appConfig from 'config/app-config'; import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'; import LocalStorageKeys from 'constants/local-storage-keys'; import { setContext } from '@apo

我试图在返回Apollo客户端的类中构建一个简单的函数。这是我的密码:

import appConfig from 'config/app-config';
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import LocalStorageKeys from 'constants/local-storage-keys';
import { setContext } from '@apollo/client/link/context';

export class ApolloClientServiceImpl {
  private cache: InMemoryCache;
  constructor() {
    this.cache = new InMemoryCache();
  }

  createApolloClient(idToken: string): unknown {
    const httpLink = createHttpLink({
      uri: appConfig.hasura.url,
    });
    const authLink = setContext((_, { headers }) => {
      let bearerToken = localStorage.getItem(LocalStorageKeys.TOKEN);
      if (idToken) {
        bearerToken = idToken;
      }
      return {
        headers: {
          ...headers,
          authorization: bearerToken ? `Bearer ${bearerToken}` : '',
        },
      };
    });
    return new ApolloClient({
      link: authLink.concat(httpLink),
      cache: this.cache,
    });
  }
}

我的问题在于
createApollopClient
函数的返回类型。如果我将其设置为
ApolloClient
,并在return语句中执行以下操作:

return new ApolloClient<InMemoryCache>({
      link: authLink.concat(httpLink),
      cache: this.cache,
    });

然后将返回类型更改为
ApolloClient
,这样可以修复所有错误。感谢Alluan Hadad。

查看我的课程。返回类型为
ApolloClient

从“apollo cache inmemory”导入{InMemoryCache,NormalizedCacheObject};
从“apollo客户端”导入{apollo客户端};
从“apollo client/core/LocalState”导入{FragmentMatcher};
从“阿波罗链接”导入{apollo链接};
从“阿波罗链接错误”导入{onError};
从“阿波罗链接http”导入{HttpLink};
枚举EApolloCLientCredentials{
默认值\u OMIT=“OMIT”,
INCLUDE=“INCLUDE”,
相同来源=“相同来源”,
}
类ClsApolloClient{
私有的httpLink:httpLink;
私人凭证:EApolloCLientCredentials;
private _fragmentMatcher:fragmentMatcher |未定义;
private _graphqlServerUrl:string;
私有缓存内存规则:记录;
私人阿波罗客户:阿波罗客户;
建造师(
graphqlServerUrl:字符串,
凭据:EApolloCLientCredentials=EApolloCLientCredentials.DEFAULT\u省略,
碎片匹配器?:碎片匹配器,
cacheInMemoryRules:Record={}
) {
这是。_graphqlServerUrl=graphqlServerUrl;
这是。_凭证=凭证;
这个。_fragmentMatcher=fragmentMatcher;
这。_cacheInMemoryRules=cacheInMemoryRules;
this.\u apolloClient=this.initApolloClient();
}
获取apolloClient():apolloClient{
把这个还给我;
}
获取httpLink():httpLink{
返回此。\u httpLink;
}
获取cacheInMemoryRules():记录{
返回此。\u缓存内存规则;
}
设置cacheInMemoryRules(cacheInMemoryRules:记录){
这。_cacheInMemoryRules=cacheInMemoryRules;
this.\u apolloClient=this.initApolloClient();
}
获取凭据():EApolloCLientCredentials{
返回此。\u凭据;
}
设置凭据(凭据:EApolloCLientCredentials){
这是。_凭证=凭证;
this.\u apolloClient=this.initApolloClient();
}
get fragmentMatcher():fragmentMatcher |未定义{
返回此文件。\u碎片匹配器;
}
设置碎片匹配器(碎片匹配器:碎片匹配器|未定义){
这个。_fragmentMatcher=fragmentMatcher;
this.\u apolloClient=this.initApolloClient();
}
私有initApolloClient():ApolloClient{
const errorLink=onError({graphQLErrors,networkError})=>{
如果(图形错误)
forEach({message,locations,path})=>
console.log(
`[GraphQL错误]:消息:${Message},位置:${locations},路径:${Path}`
)
);
if(networkError)console.log(`[networkError]:${networkError}`);
});
此.\u httpLink=新的httpLink({
uri:this.\u graphqlServerUrl,
凭证:此.\u凭证,
});
const links=[errorLink,this.\u httpLink];
const Apollo客户端:Apollo客户端=新Apollo客户端(
{
链接:阿波罗链接。从(链接),
缓存:新的InMemoryCache({
…这个.\u缓存内存规则,
addTypename:false,
}),
碎片匹配器:这个,
}
);
返回客户;
}
}
导出{EApolloCLientCredentials,ClsApolloClient};

新客户端
坏了。应该是
new ApolloClient
@AluanHaddad,结果证明这解决了问题。谢谢!没问题。指定显式类型参数是一种反模式,尤其是在传递值时。正确的类型脚本尽可能利用类型推断
Type 'InMemoryCache' is not assignable to type 'ApolloCache<InMemoryCache>'.
  Types of property 'restore' are incompatible.
    Type '(data: NormalizedCacheObject) => InMemoryCache' is not assignable to type '(serializedState: InMemoryCache) => ApolloCache<InMemoryCache>'.
      Types of parameters 'data' and 'serializedState' are incompatible.
        Type 'InMemoryCache' is not assignable to type 'NormalizedCacheObject'.
          Index signature is missing in type 'InMemoryCache'.ts(2322)
    return new ApolloClient({
      link: authLink.concat(httpLink),
      cache: this.cache,
    });
import { InMemoryCache, NormalizedCacheObject } from "apollo-cache-inmemory";
import { ApolloClient } from "apollo-client";
import { FragmentMatcher } from "apollo-client/core/LocalState";
import { ApolloLink } from "apollo-link";
import { onError } from "apollo-link-error";
import { HttpLink } from "apollo-link-http";

enum EApolloCLientCredentials {
    DEFAULT_OMIT = "omit",
    INCLUDE = "include",
    SAME_ORIGIN = "same-origin",
}

class ClsApolloClient {
    private _httpLink: HttpLink;
    private _credentials: EApolloCLientCredentials;
    private _fragmentMatcher: FragmentMatcher | undefined;
    private _graphqlServerUrl: string;
    private _cacheInMemoryRules: Record<string, any>;
    private _apolloClient: ApolloClient<NormalizedCacheObject>;

    constructor(
        graphqlServerUrl: string,
        credentials: EApolloCLientCredentials = EApolloCLientCredentials.DEFAULT_OMIT,
        fragmentMatcher?: FragmentMatcher,
        cacheInMemoryRules: Record<string, any> = {}
    ) {
        this._graphqlServerUrl = graphqlServerUrl;
        this._credentials = credentials;
        this._fragmentMatcher = fragmentMatcher;
        this._cacheInMemoryRules = cacheInMemoryRules;

        this._apolloClient = this.initApolloClient();
    }

    get apolloClient(): ApolloClient<NormalizedCacheObject> {
        return this._apolloClient;
    }

    get httpLink(): HttpLink {
        return this._httpLink;
    }

    get cacheInMemoryRules(): Record<string, any> {
        return this._cacheInMemoryRules;
    }
    set cacheInMemoryRules(cacheInMemoryRules: Record<string, any>) {
        this._cacheInMemoryRules = cacheInMemoryRules;
        this._apolloClient = this.initApolloClient();
    }

    get credentials(): EApolloCLientCredentials {
        return this._credentials;
    }

    set credentials(credentials: EApolloCLientCredentials) {
        this._credentials = credentials;
        this._apolloClient = this.initApolloClient();
    }

    get fragmentMatcher(): FragmentMatcher | undefined {
        return this._fragmentMatcher;
    }

    set fragmentMatcher(fragmentMatcher: FragmentMatcher | undefined) {
        this._fragmentMatcher = fragmentMatcher;
        this._apolloClient = this.initApolloClient();
    }

    private initApolloClient(): ApolloClient<NormalizedCacheObject> {
        const errorLink = onError(({ graphQLErrors, networkError }) => {
            if (graphQLErrors)
                graphQLErrors.forEach(({ message, locations, path }) =>
                    console.log(
                        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
                    )
                );

            if (networkError) console.log(`[Network error]: ${networkError}`);
        });

        this._httpLink = new HttpLink({
            uri: this._graphqlServerUrl,
            credentials: this._credentials,
        });
        const links = [errorLink, this._httpLink];
        const apolloClient: ApolloClient<NormalizedCacheObject> = new ApolloClient(
            {
                link: ApolloLink.from(links),
                cache: new InMemoryCache({
                    ...this._cacheInMemoryRules,
                    addTypename: false,
                }),
                fragmentMatcher: this._fragmentMatcher,
            }
        );
        return apolloClient;
    }
}

export { EApolloCLientCredentials, ClsApolloClient };