0
0
Typescriptprogramming~15 mins

Generic functions with arrays in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create arrays of numbers and strings
Create a variable called numbers and set it to the array [10, 20, 30]. Then create a variable called words and set it to the array ["apple", "banana", "cherry"].
Typescript
Need a hint?

Use const to create the arrays exactly as shown.

2
Create a generic function called getFirstItem
Create a generic function called getFirstItem with a type parameter T. It should take one parameter called items which is an array of type T. The function should return the first element of the items array.
Typescript
Need a hint?

Use function getFirstItem<T>(items: T[]): T and return the first item with items[0].

3
Call getFirstItem with arrays
Call getFirstItem with the numbers array and store the result in a variable called firstNumber. Then call getFirstItem with the words array and store the result in a variable called firstWord.
Typescript
Need a hint?

Store the results in firstNumber and firstWord variables.

4
Print the results
Print the value of firstNumber and firstWord using console.log.
Typescript
Need a hint?

Use console.log(firstNumber) and console.log(firstWord) to print the results.