0

longtime typescript veteran here, but i'm stuck making proper types for an rpc api system. i've boiled it down to this simple example:


export function augment<
    Data,
    Method extends (data: Data, ...args: any[]) => void,
  >(method: Method) {

  return method
}

const example1 = augment<string>((data, x: number) => {})
  //                     ^
  // ERROR: Expected 2 type arguments, but got 1. ts (2558)

const example2 = augment<string, any>((data, x: number) => {})
  //                                   ^
  //            must be automatically known (string, not any)


const example3 = augment<string, any>((data, x: number) => {})
  //  ^
  // must preserve the method type, should be:
  //   (data: string, x: number) => void

  • it appears generics must be passed "all or nothing"
  • i can't seem to just provide the Data type without also providing Method type
  • however i don't know the Method type ahead of time. it's usually defined inline in the augment function call
  • so i need the augment function to receive the Method type as inferred from the method input
  • my actual use-case is more complex: i'm really accepting a recursive object structure which can contain any number of methods, all of which will accept the same Data type first argument
  • it's vital that the returned method has the exact type of the method input, since the methods will be literally defined inline the function call (can't use typeof method)

is there a different approach? if this is a typescript limitation, what workarounds or compromises might be considered?
  thanks

ChaseMoskal
  • 7,151
  • 5
  • 37
  • 50

0 Answers0