1

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

Let's say I want pass refetch function as a prop on a component, and this is what I am doing.

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

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

I have to

  1. find refetch function type definition
  2. import required types and etcs. e.g. ApolloQueryResult
  3. write refetch prop as it is in ObservableQuery

, and I am thinking there has to be an easier way.

How would you define the same function type as a prop other than just copy things around like I do?

1 Answer 1

1

You can use typeof to get type of some object, including existing function.

For example

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
}

You have not just function refresh but method refresh of class ObservableQuery. To extract type of method you should use indexed access type like this

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>

Not thet no need for typeof keyword anymore as indexed access provides type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.