0
0
Typescriptprogramming~20 mins

Why generics are needed in Typescript - See It in Action

Choose your learning style9 modes available
Why generics are needed
📖 Scenario: Imagine you are building a simple storage box system. You want to store different types of items safely without mixing them up or losing their type information.
🎯 Goal: You will create a generic storage box function that can hold any type of item and return it safely, showing why generics help keep code flexible and type-safe.
📋 What You'll Learn
Create a function called storeItem that takes one parameter called item and returns it.
Create a variable called numberBox that stores a number using storeItem.
Create a variable called stringBox that stores a string using storeItem.
Use a generic type parameter T in the storeItem function to keep the type of item.
Print the values of numberBox and stringBox.
💡 Why This Matters
🌍 Real World
Generics are used in many programming tasks where you want to write reusable code that works with different data types, like storing user data, handling lists, or working with APIs.
💼 Career
Understanding generics is important for writing safe and reusable code in TypeScript, which is widely used in web development jobs.
Progress0 / 4 steps
1
Create a simple function to store an item
Create a function called storeItem that takes one parameter called item of type any and returns it.
Typescript
Need a hint?

Use function storeItem(item: any) { return item; } to accept any type.

2
Store a number and a string using the function
Create a variable called numberBox and assign it the result of calling storeItem with the number 42. Then create a variable called stringBox and assign it the result of calling storeItem with the string 'hello'.
Typescript
Need a hint?

Use const numberBox = storeItem(42); and const stringBox = storeItem('hello');.

3
Make the function generic to keep the item type
Change the storeItem function to use a generic type parameter T. The parameter item should be of type T and the function should return type T.
Typescript
Need a hint?

Use function storeItem<T>(item: T): T { return item; } to keep the type.

4
Print the stored values to see the result
Write two console.log statements to print numberBox and stringBox.
Typescript
Need a hint?

Use console.log(numberBox); and console.log(stringBox); to show the values.