網站搜尋

javascript - ApolloClient 客戶端的類型


我有一個函數,我把客戶端作為參數傳入,並從我的應用程式等中刪除令牌:

  const logOut = async (client: ApolloClient<unknown>) => {...};
return (
    <ApolloConsumer>
      {(client: ApolloClient<unknown>) => (
        <SafeAreaView style={styles.safeAreaViewContainer}>
                <View style={styles.buttonContainer}>
                <Button
                  onPress={() => logOut(client)}
                  style={styles.button}
                />
              </View>
             </SafeAreaView>
      )}
    </ApolloConsumer>
  );
};

現在我對 ApolloClient 類型使用 unknown,並且它可以運作。但我在這裡實際上應該使用什麼?

答案#1

如果你查看 @apollo/client/react/context/ApolloConsumer.d.ts,你可以看到 client 的類型是 ApolloClient<object>(在舊版 react-apollo 中,類型是 ApolloClient<any>)

import React from "react";
import { ApolloClient } from "../../core";
export interface ApolloConsumerProps {
  children: (client: ApolloClient<object>) => React.ReactChild | null;
}
export declare const ApolloConsumer: React.FC<ApolloConsumerProps>;
//# sourceMappingURL=ApolloConsumer.d.ts.map

我不會明確指定client的類型。TypeScript 足夠智能,可以自動推斷它。

如果你仍然想寫一個更嚴格的類型,ApolloClient 中的泛型是 TCacheShape,它取決於你與 Apollo 一起使用的緩存。

例如,你正在使用 InMemoryCache,泛型類型是 NormalizedCacheObject

export interface NormalizedCacheObject {
  [dataId: string]: StoreObject | undefined;
}

export interface StoreObject {
  __typename?: string;
  [storeFieldName: string]: StoreValue;
}