TypeScript from JavaScript

Lesson 3 of 6

Generics

Generics let you write a function or type once and have it work correctly with whatever type gets passed in, without losing type safety.

TypeScript

Think of <T> as a placeholder: "whatever type you give me, I'll give the same type back out." The compiler figures out T automatically from the argument you pass, and still catches mistakes, firstElement([1, 2, 3])[0].toUpperCase() would be a compile error because that element is a number, not a string.

📝 Generics Quiz

Passing score: 70%
  1. 1.A generic type parameter is conventionally named a single capital letter, most commonly ____.

  2. 2.What is the main benefit of using generics?

  3. 3.firstElement<string>(...) and firstElement<number>(...) can share the exact same function implementation.