Home > front end >  How to type a variable that implements a function interface that takes a generic?
How to type a variable that implements a function interface that takes a generic?

Time:09-17

I'm sure this is a dupe but for the life of me can't find it. I have a function interface that takes a type parameter:

interface A<T> {
    (foo: T): void
}

And I want to assign an arrow function that satisfies that interface to a variable:

const x: A = <T>(foo: T) => { console.log(foo) };

But this of course fails to compile, because A requires the type parameter. This also fails:

const x: A<T> = <T>(foo: T) => { console.log(foo) };

because the type variable T is not in scope on the LH of the assignment. How do I actually declare this?

Playground

CodePudding user response:

This is a generic type, which includes a function that uses the generic parameter:

interface A<T> { (foo: T): void }

This is a non generic type that includes a generic function:

interface A { <T>(foo: T): void }

You want this one.

The key here is that A does not enforce any type for T. That is done when the function is called, which is why it needs to to be on the function declaration, and not the interface or type alias.

Playground


And personally, I think this will be much clearer if you use type instead of interface.

type A = <T>(foo: T) => void
  • Related