0
0
Typescriptprogramming~15 mins

Generic arrow functions in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Generic Arrow Functions
📖 Scenario: You are building a small utility in TypeScript to work with different types of data. You want to create a generic arrow function that can take any type of input and return it unchanged. This is useful when you want to write flexible code that works with many data types.
🎯 Goal: Create a generic arrow function called identity that takes a value of any type and returns the same value. Then test it with a string and a number.
📋 What You'll Learn
Create a generic arrow function named identity with a type parameter T.
The function should take one parameter value of type T and return a value of type T.
Call identity with a string and store the result in resultString.
Call identity with a number and store the result in resultNumber.
Print both resultString and resultNumber.
💡 Why This Matters
🌍 Real World
Generic functions help write reusable code that works with many data types, saving time and reducing errors.
💼 Career
Understanding generics is important for TypeScript developers to build flexible and type-safe applications.
Progress0 / 4 steps
1
Create a generic arrow function
Create a generic arrow function called identity with a type parameter T. It should take one parameter value of type T and return the same value.
Typescript
Need a hint?

Use the syntax const identity = <T>(value: T): T => value; to create a generic arrow function.

2
Call the generic function with a string
Call the generic arrow function identity with the string "Hello" and store the result in a variable called resultString.
Typescript
Need a hint?

Call identity with "Hello" and specify the type string.

3
Call the generic function with a number
Call the generic arrow function identity with the number 42 and store the result in a variable called resultNumber.
Typescript
Need a hint?

Call identity with 42 and specify the type number.

4
Print the results
Print the values of resultString and resultNumber using two separate console.log statements.
Typescript
Need a hint?

Use console.log(resultString); and console.log(resultNumber); to print the results.