Maximus Maximus - 12 days ago 7
TypeScript Question

What does the following mean ` <TFunction extends Function>(target: TFunction) => TFunction | void`

I'm looking at

lib.d.ts
file and there is the following there:

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


I don't quite understand the syntax. Can anyone help?

What I understand is that new type
ClassDecorator
is declared. This type extends from the function. But what is this:
<TFunction extends Function>
? And why is arrow used there?

Answer

It's declaring a type for a generic function with the base form of

<T>(target: T) => T | void;

Example

type MyFuncType = <T>(target: T) => T | void;

var myFunc: MyFuncType = <T>(target: T) => {
    return target;
}

var stringOrVoidResult = myFunc<string>("test");
var numberOrVoidResult = myFunc<number>(123);

TFunction extends Function means that the type that you are declaring the generic function to be when you use it, has to be of the type Function, which all classes are.

Example

class Animal {
    Eat: () => void;
    Sleep: () => void;
}

type MyFuncType = <T extends Animal>(target: T) => T | void;

var myFunc: MyFuncType = <T>(target: T) => {
    return target;
}

var stringOrVoidResult = myFunc<string>("test"); // Error, string is not a subtype of Animal
var numberOrVoidResult = myFunc<number>(123); // Error, number is not a subtype of Animal

class Dog extends Animal {

}

var dogOrVoidResult = myFunc<Dog>(new Dog()); //Ok, Dog is Animal

In the above examples, you don't really have to specify the generic type of the function as the compiler could understand that from the input argument. Although that is not always the case.

var stringOrVoidResult = myFunc("test");
var numberOrVoidResult = myFunc(123);
var dogOrVoidResult = myFunc(new Dog());
Comments