AI Hints
TypeScript · Lesson 53 of 120

Generic Functions

Type parameters.

⏱ 2 min read▶ Video at 41:58🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Let's make first item generic. T stands for whatever type the list holds. The parameter is a list of T, and the result is a T, or undefined for an empty list.

Generic Functions
From the video: Generic Functions
  • T is a placeholder
  • List of T
  • Returns T

A generic firstItem

For a list of strings, T becomes string. For numbers, T becomes number. Now the store has string methods, and the price has number methods. Run it.

app.tstypescript
function firstItem<T>(list: T[]): T | undefined {
  return list[0];
}

const store = firstItem(["Leeds", "York"]);
const price = firstItem([849.5, 450]);

console.log(store?.toUpperCase(), price?.toFixed(2));
Output
LEEDS 849.50

Types still checked

Because store is a string, calling a number method on it is caught. Run it.

app.tstypescript
function firstItem<T>(list: T[]): T | undefined {
  return list[0];
}
const store = firstItem(["Leeds", "York"]);
store?.toFixed(2);
Output
app.ts line 5: Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'?

Summary

Type parameters in angle brackets let types flow from inputs to outputs. Next, generic constraints.

Key takeaways
  • firstItem<T>
  • T[]
  • Types flow
Next up: Generic Constraints — extends