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

Time:05-24

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

CodePudding user response:

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) => {
  // ...
};
  • Related