Maximus Maximus - 1 year ago 88
TypeScript Question

What's the difference between declaring a generic function and declaring a type for generic function

I have two examples of using generic function:

function genericFunction<TFunction extends Function>(target:TFunction): string {
return target.toString();

According to this answer, this is generic function declaration.

Then this:

declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;

According to this answer, this a type declaration for a generic function.

I can't seem to understand when each is used. Can somebody please provide examples of usage for both?

Answer Source

The first one is a generic function, it receives one argument which is of the type of the generic constraint.
It's a plain js function, and it will be part of the compiled js.

The second one is a type alias for a generic function type, for example the following functions match this type:

let fn1: ClassDecorator = function<T extends Function>(target: T): void {
    // ...

let fn2: ClassDecorator = function<T extends Function>(target: T): T {
    // ...

The type is only in typescript, it won't be present in the compiled js.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download