简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM