These are signs of generics. When you see
testfunc<T>(s){ return s; }
, it means that
testfunc
can accept a generic type parameter
T
. Using
testfunc<boolean>(4)
is providing a specific type argument (
boolean
) for that type parameter. In the given example, it may not have much impact since
testfunc
isn't utilizing
T
, but consider this:
function foo(arg: string) {
let numbers: Array<number> = [];
numbers[0] = arg; // Error: Type 'string' is not assignable to type 'number'.
}
In this case, numbers
is defined as an array of number
, which leads to an error when trying to assign a string value like arg
.
Now, take a look at this alternative scenario:
function foo<T>(arg: T) {
let numbers: Array<T> = [];
numbers[0] = arg; // Error
}
Here, foo
doesn't need to know the content of numbers
, just that it will match the type of arg
. This allows for valid calls like:
foo<number>(4);
foo<string>("bar");
While I've shown explicit type arguments in these calls, TypeScript can often infer them automatically:
foo(4);
foo("bar");