Ilja
Ilja

Reputation: 46479

How to access <T> from function types in following syntax

Below is abstracted version of types in a project I am working on

// types.ts
interface Methods {
  request<T>(params: RequestParams): Promise<T>;
}

// implementation.ts
public request: Methods["request"] = async <T>(params) => {
  // ...
};

I was assuming that I would be able to access <T> as above, but as soon as I add it, params becomes untyped / any for some reason

Upvotes: 1

Views: 102

Answers (1)

Guerric P
Guerric P

Reputation: 31805

When you write an assignment with a generic type, TypeScript won't infer the type of an assigned value from the variable type. It just verifies that the type of the assigned value (<T>(params: any): Promise<T>) is compatible with the variable type (<T>(params: RequestParams): Promise<T>), according to the duck typing rules.

So you shouldn't expect params to be typed automatically, but you should type it yourself instead:

// types.ts
interface Methods {
  request<T>(params: RequestParams): Promise<T>;
}

// implementation.ts
public request: Methods["request"] = async <T>(params: RequestParams) => {
  // ...
};

TypeScript playground link

Upvotes: 2

Related Questions