Type Parameters

The problem generics solve. You want one function that works with arrays of anything. Without generics you have two bad options: return any and lose the type, or write the function once per type.

A type parameter is a placeholder the caller fills in, usually without noticing.

Try it

Change the return type to just T and see what the compiler says about an empty array. It is right: items[0] on an empty array is undefined.

loading editor…

checking…

The type flows through. The last line is rejected because first was given numbers, so it cannot produce a string. Hover over a and b in your editor to see the types it worked out.

You rarely pass the type explicitly. Inference works it out from the arguments, which is why generics are far more common in code you read than in code you write.

T is a convention rather than a rule. Name it for what it holds when that helps: <Item>, <Row>, <Payload>.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Constraints and Generic Types →
← Back