Maximus Maximus - 3 months ago 24
TypeScript Question

What's the purpose of <T> inside `function genericFunction<T>(arg:T): string {}`

I'm reading about generic functions in TypeScript here. The author provides an example of a generic function:

function genericFunction<T>(arg:T): string {
return arg.toString();

I'm curios of the purpose of
. Without it, this

function genericFunction(arg:T): string {
return arg.toString();

will gives an error
Error:(1, 30) TS2304:Cannot find name 'T'.
. So is it somehow telling compiler that the type
specified in the function should be treated as generic? So to define a simple function we need to use name, to define a generic function, we need to use
name<type here>

At the bottom, the author shows another usage of

function xValue<T extends Point>

which is used to tell a compiler that the type
will have properties defined on the

I understand what a generic function is. The question is about the purpose of
identifier in generic function syntax.

function genericFunction<T>

This <T> here is the introduction of the generic type to this function. You're basically saying we have a function here, and we are using a generic type in it, and it is T.

Introducing the T there allows you to use it as a type in the rest of the function.

If you omit <T>, the function does not know you're using a generic type and it will not work.