1

https://github.com/apollographql/apollo-client/blob/4e9f370f262c171409037dae24fadccb61c35d13/packages/apollo-client/src/core/ObservableQuery.ts#L303

假设我想将传递refetch函数作为组件上的道具,这就是我正在做的事情。

import { ApolloQueryResult } from "apollo-client"
interface MyQueryVariables{ ... }
interface MyQueryResult{ ... }

interface Props {
  refetch: (
    variables?: MyQueryVariables | undefined
  ) => Promise<ApolloQueryResult<MyQueryResult>>
}

我必须

  1. 查找 refetch 函数类型定义
  2. 导入所需的类型等。例如ApolloQueryResult
  3. 像在 ObservableQuery 中一样写 refetch prop

,我认为必须有一种更简单的方法。

除了像我一样复制东西之外,你如何定义与道具相同的函数类型?

4

1 回答 1

1

您可以使用typeof获取某些对象的类型,包括现有函数。

例如

function refetch(variables?: TVariables): Promise<ApolloQueryResult<TData>>
// Somewhere in code
type refreshFuncType = typeof refetch; // Now refreshFuncType is of type (variables?: TVariables) => Promise<ApolloQueryResult<TData>>

interface Props {
    refetch: refreshFuncType
}

你不仅有class 的function refresh方法。要提取方法的类型,您应该使用这样的索引访问类型refreshObservableQuery

type refreshFuncType = ObservableQuery['refetch']; // Now refreshFuncType is of type (variables?: TVariables) => Promise<ApolloQueryResult<TData>>
// As ObservableQuery is generic you may provide specific type using ObservableQuery<type1, type2>

不再需要typeof关键字,因为索引访问提供了类型。

于 2019-05-19T13:11:19.997 回答