In typescript how do you add generics to a function you expect to invoke with .call

Viewed 270
interface Wrapped<T> {
  data: T;
}

interface BetterWrapper<T> {
  betterData: T;
}

function abc<T>(test: Wrapped<T>): BetterWrapper<T> {
  return {betterData: test.data}
}

const result = abc<string>.call({}, { data: 'hello' });

Given something like the above, I'm seeing an error that says cannot find name call. I'm guessing that's because the return type is a string, if so what's the right now to represent this in typescript?

1 Answers

Here's a solution by declaring an interface where call has the required generic signature: you can use abc.call<string>(...) or just abc.call(...) and let the type parameter be inferred.

interface AbcInterface {
  <T>(test: Wrapped<T>): BetterWrapper<T>;
  call<T>(thisObj: object, arg: Wrapped<T>): BetterWrapper<T>;
}
const abc: AbcInterface = test => ({betterData: test.data});

// result: BetterWrapper<string>
const result = abc.call({}, { data: 'hello' });

Playground Link

Related