【问题标题】:ApolloClient client's TypeApolloClient 客户端的类型
【发布时间】:2021-01-01 03:15:57
【问题描述】:

我有一个函数,我将客户端作为参数传递并从我的应用程序中删除令牌等:

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

现在我正在使用unknown作为 ApolloClient 类型,它可以工作。但是我应该在这里实际使用什么?

【问题讨论】:

    标签: javascript reactjs typescript react-native apollo


    【解决方案1】:

    如果你查看@apollo/client/react/context/ApolloConsumer.d.ts,你可以看到客户端的类型是ApolloClient&lt;object&gt;(在旧的react-apollo中类型是ApolloClient&lt;any&gt;

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-18
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      相关资源
      最近更新 更多