Maximus Maximus - 13 days ago 6
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
<T>
. 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
T
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>
identifier?

At the bottom, the author shows another usage of
<T>
:

function xValue<T extends Point>


which is used to tell a compiler that the type
T
will have properties defined on the
Point
interface.

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

Answer
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.