0
0
Typescriptprogramming~15 mins

Generic function syntax in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Generic function syntax
📖 Scenario: You are building a simple utility library in TypeScript that can work with different types of data.
🎯 Goal: Create a generic function that returns the first element of any array, no matter what type of elements it holds.
📋 What You'll Learn
Create a generic function called getFirstElement
The function should accept one parameter called arr which is an array of generic type T
The function should return the first element of the array with type T
Call the function with a number array and a string array
Print the results of both calls
💡 Why This Matters
🌍 Real World
Generic functions are useful in libraries and frameworks where you want to write code that works with many data types without repeating yourself.
💼 Career
Understanding generics is important for TypeScript developers to write flexible and safe code, which is highly valued in professional software development.
Progress0 / 4 steps
1
Create a number array
Create a variable called numbers and assign it the array [10, 20, 30].
Typescript
Need a hint?

Use const numbers = [10, 20, 30]; to create the array.

2
Create a string array
Create a variable called words and assign it the array ["apple", "banana", "cherry"].
Typescript
Need a hint?

Use const words = ["apple", "banana", "cherry"]; to create the array.

3
Create the generic function
Create a generic function called getFirstElement with a type parameter T. It should take one parameter arr of type T[] and return the first element of arr with type T.
Typescript
Need a hint?

Use function getFirstElement<T>(arr: T[]): T { return arr[0]; }.

4
Call the function and print results
Call getFirstElement with numbers and assign the result to firstNumber. Call getFirstElement with words and assign the result to firstWord. Then print firstNumber and firstWord using console.log.
Typescript
Need a hint?

Use const firstNumber = getFirstElement(numbers); and console.log(firstNumber); similarly for words.