0
0
Typescriptprogramming~15 mins

How TypeScript infers generic types - Try It Yourself

Choose your learning style9 modes available
How TypeScript infers generic types
📖 Scenario: You are building a small utility to work with arrays of different types. You want to create a function that can accept any type of array and return the first element. TypeScript can help by figuring out the type automatically using generics.
🎯 Goal: Build a generic function in TypeScript that returns the first element of any array, letting TypeScript infer the type automatically.
📋 What You'll Learn
Create a generic function called getFirstElement that accepts an array of any type.
Use TypeScript's generic type inference to let the function know the type of the array elements.
Call the function with different types of arrays: numbers and strings.
Print the returned first element from each call.
💡 Why This Matters
🌍 Real World
Generic functions are used in many libraries and applications to write reusable code that works with different data types safely.
💼 Career
Understanding how TypeScript infers generic types is important for writing clean, maintainable, and type-safe code in professional TypeScript projects.
Progress0 / 4 steps
1
Create an array of numbers
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 generic function to get the first element
Create a generic function called getFirstElement with a type parameter T. It should accept a parameter arr of type T[] and return a value of type T.
Typescript
Need a hint?

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

3
Call the generic function with number and string arrays
Call getFirstElement with the numbers array and assign the result to firstNumber. Then create a variable words with the array ["apple", "banana", "cherry"] and call getFirstElement with words, assigning the result to firstWord.
Typescript
Need a hint?

Call the function like getFirstElement(numbers) and getFirstElement(words).

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

Use console.log(firstNumber); console.log(firstWord); to print the values.