1

In Typescript, is there a way to refer to a function type with generics, without having to instantiate the generics? (Passing them to be instantiated when the function is actually called).

For example, I have the following type:

type FetchPageData<T> = (client : APIClient<T>) => T; 

where APIClient is an abstract class like this:

export abstract class APIClient<T> { abstract getData(demoDataIsSelected : boolean, queryParameters ?: ApiQueryParameters) : T; } 

I want to create a function of this type, but if I try:

fetchPageData : FetchPageData = client => { return client.getData(x, y); } 

Typescript requires that I provide the generic type for T. What I want is similar to what we do when refering to a function definition, instead of calling it. Similarly I would expect this to refer to the type definition without requiring the T, because the T concerns only the calling of the function.

If not like this, what is the syntax for me to get a T and pass it to FetchPageData on the instantiation? (It has to be with const syntax, instead of function, because I'm actually asigning with useCallback on react)

1 Answer 1

2

I figured it out right after posting this:

By putting the <T> before the equal sign, I was using T as a generic for the creation of the function, instead of defining the FetchPageData as a function type that takes a generic argument. The correct syntax would be:

type FetchPageData = <T>(client : APIClient<T>) => T; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.