Generic functions with arrays
📖 Scenario: You are building a small utility to work with lists of items. You want to create a generic function that can take an array of any type and return the first item. This helps you avoid writing the same code for different types of arrays.
🎯 Goal: Create a generic function called getFirstItem that takes an array of any type and returns the first element. Then test it with arrays of numbers and strings.
📋 What You'll Learn
Create a generic function called
getFirstItem with a type parameter T.The function should accept one parameter called
items which is an array of type T.The function should return the first element of the
items array.Create a variable
numbers with the array [10, 20, 30].Create a variable
words with the array ["apple", "banana", "cherry"].Call
getFirstItem with numbers and print the result.Call
getFirstItem with words and print the result.💡 Why This Matters
🌍 Real World
Generic functions are used in many programs to handle data of different types without repeating code. For example, utility libraries use generics to work with arrays, lists, or collections.
💼 Career
Understanding generics is important for TypeScript developers because it helps write flexible and safe code, which is highly valued in software development jobs.
Progress0 / 4 steps