Home > Enterprise >  Generic typings for one property on an Interface in TypeScript
Generic typings for one property on an Interface in TypeScript

Time:02-13

I'm trying to type a method, that is part of an interface and I need it to take a generic. Below is a simplified example of what I want. I want users of the API be able to type method with a generic. However I don't know here to specify it.

Can anyone explain to me how to add generics to method on Main here? Without the generics being passed to the Main interface but to the actual method.

interface Method<T> {
  (t: T): T
}

interface Main {
  method: Method
}

const main: Main = {
  method: id => id,
}

main.method<string>('test')

CodePudding user response:

You defined a generic type that happens to be a function. What you really want is a generic function. To do that you need to put the generic type list on the signature, not the type

interface Method {
  <T>(t: T): T
}

interface Main {
  method: Method
}

const main: Main = {
  method: id => id,
}

main.method<string>('test')

Playground Link

  • Related