0
0
Typescriptprogramming~15 mins

Generic interface declaration in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Generic Interface Declaration
📖 Scenario: You are building a simple system to store information about different types of items. Each item has a name and a value. The value can be of any type, like a number, string, or boolean.
🎯 Goal: Create a generic interface called Item that can hold a name as a string and a value of any type. Then create two objects using this interface: one with a number value and one with a string value.
📋 What You'll Learn
Create a generic interface called Item with a type parameter T.
The interface must have a name property of type string.
The interface must have a value property of type T.
Create a variable called numberItem of type Item<number> with name as "Age" and value as 30.
Create a variable called stringItem of type Item<string> with name as "Color" and value as "Blue".
Print both variables to the console.
💡 Why This Matters
🌍 Real World
Generic interfaces help you write flexible and reusable code that works with many data types, like storing different kinds of items in a shopping cart or settings.
💼 Career
Understanding generics is important for TypeScript developers to build scalable and type-safe applications, which is a valuable skill in many software development jobs.
Progress0 / 4 steps
1
Create the generic interface
Create a generic interface called Item with a type parameter T. It should have a name property of type string and a value property of type T.
Typescript
Need a hint?

Use interface Item<T> to declare a generic interface with a type parameter T.

2
Create a number item
Create a variable called numberItem of type Item<number> with name set to "Age" and value set to 30.
Typescript
Need a hint?

Use const numberItem: Item<number> = { name: "Age", value: 30 }; to create the variable.

3
Create a string item
Create a variable called stringItem of type Item<string> with name set to "Color" and value set to "Blue".
Typescript
Need a hint?

Use const stringItem: Item<string> = { name: "Color", value: "Blue" }; to create the variable.

4
Print the items
Print numberItem and stringItem to the console using two separate console.log statements.
Typescript
Need a hint?

Use console.log(numberItem); and console.log(stringItem); to print the objects.