Home > Net >  How can I use generics in a function returned from a factory function that is typed?
How can I use generics in a function returned from a factory function that is typed?

Time:01-17

I have defined a type for a factory function where one of the functions returned uses a generic.

type Factory = (param: string) => {
  func: <T extends {}>(param: string) => Promise<T>,
};

const factory: Factory = __factoryParam => ({
  func: async <T>(__param) => {
    return Promise.resolve({} as T);
  },
});

When I hover over the __param parameter in the code above I get the error Parameter '__param' implicitly has an 'any' type.ts(7006).

If I get rid of the generic, then __param is typed correctly. If I explicitly type the parameter in the implementation, it of course works:

func: async <T>(__param: string) => {

What am I doing wrong here?

CodePudding user response:

This is a case where it's fine to use as any on the return value and just omit the generic in the implementation:

TS Playground

type Factory = (param: string) => {
  func: <T extends {}>(param: string) => Promise<T>,
};

const factory: Factory = __factoryParam => ({
  async func (__param) {
    return Promise.resolve({}) as any;
  },
});

const result = factory('str').func<{msg: 'hello'}>('str2'); // Promise<{ msg: 'hello' }>
  •  Tags:  
  • Related