Describing a type for a generic function using the basic format 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
indicates that the specified generic function's type, when used, must be of the type Function
, which encompasses all classes.
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, as string is not an Animal subtype
var numberOrVoidResult = myFunc<number>(123); // Error, as number is not an Animal subtype
class Dog extends Animal {
}
var dogOrVoidResult = myFunc<Dog>(new Dog()); //Ok, since Dog is an Animal
In the given examples, specifying the generic function's type may not always be necessary as it can be inferred from the input argument by the compiler. However, this is not always the case.
var stringOrVoidResult = myFunc("test");
var numberOrVoidResult = myFunc(123);
var dogOrVoidResult = myFunc(new Dog());