TestingDocs.com logoTestingDocs.com
Automation learning lab
TestingDocs • Self-paced course

Playwright Automation
Self Study Guide

Start from zero. Learn JavaScript and TypeScript, automate browsers, and build reliable end-to-end tests.

60 chaptersBeginner friendlyHands-on practice
TypeScript / Chapter 27 of 60~12 min • Beginner
Chapter 27TypeScript

Generics

Generics let a function preserve type information across inputs and outputs. A type parameter such as T represents a type supplied or inferred at a call site. This makes reusable helpers type-safe without resorting to any.

How it works

Step-by-step walkthrough

  1. Define a generic function
  2. Call with a string
  3. Call with a number

Example

TypeScript
function first<T>(items: T[]): T | undefined {
  return items[0];
}
console.log(first(['QA']), first([42]));
Expected result: QA 42
💡 Point to remember
Account for empty arrays in return types.

✎ Your practice task

Call first with an empty string array.

Knowledge check

What is T in this example?

🌐 Continue learning