gus3001
gus3001

Reputation: 919

How do you use a Typescript Function Interface with a Generic type?

Let's consider we have the following function interface:

interface SomeFunction<T> {(arg: T) :T}

We can use the interface like so:

const myFun: SomeFunction<string> = arg => arg;

But the issue with that is we specify the generic type T as string. How can we leave T generic?

The only way I see how is basically not using SomeFunction in the functions signature. Like so:

function myFun2<T>(arg: T): T {
    return arg;
}

But this is not nice, since there is no mention of the SomeFunction interface even though we basically match it.

Is there a better way to declare myFun2 so we make sure it conforms to SomeFunction?

Upvotes: 0

Views: 128

Answers (1)

bugs
bugs

Reputation: 15323

You can declare the interface like this

interface SomeFunction {
    <T>(arg: T) : T
}

which then lets you write your function exactly as you want to

const myFun: SomeFunction = arg => arg

Upvotes: 3

Related Questions