0
0
Typescriptprogramming~15 mins

Generic class with constraints in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Generic class with constraints
📖 Scenario: You are building a simple system to store and display information about different items. Each item must have a name property as a string. You want to create a generic class that can work with any item type, but only if it has a name property.
🎯 Goal: Create a generic class called ItemHolder that only accepts types with a name property of type string. Then, use this class to store an item and display its name.
📋 What You'll Learn
Create an interface called Named with a name property of type string
Create a generic class called ItemHolder with a type parameter constrained to Named
Add a constructor to ItemHolder that accepts an item of the generic type
Add a method getName that returns the name of the stored item
Create an object with a name property and use ItemHolder to hold it
Print the name of the stored item using the getName method
💡 Why This Matters
🌍 Real World
Generic classes with constraints help create reusable and safe code components that work with many types but enforce required properties.
💼 Career
Understanding generics and constraints is important for writing flexible and type-safe code in TypeScript, a skill valued in many software development roles.
Progress0 / 4 steps
1
Create the Named interface
Create an interface called Named with a single property name of type string.
Typescript
Need a hint?

Use the interface keyword and define name: string inside.

2
Create the generic class ItemHolder with constraint
Create a generic class called ItemHolder with a type parameter T constrained to Named. Add a constructor that accepts a parameter item of type T and stores it in a public property called item.
Typescript
Need a hint?

Use class ItemHolder<T extends Named> and a constructor with public item: T.

3
Add the getName method
Inside the ItemHolder class, add a method called getName that returns the name property of the stored item.
Typescript
Need a hint?

Define getName() that returns this.item.name.

4
Create an item and print its name
Create a constant called myItem with a name property set to "Book". Then create an instance of ItemHolder called holder using myItem. Finally, print the result of holder.getName().
Typescript
Need a hint?

Define myItem with name: "Book", create holder with new ItemHolder(myItem), then print holder.getName().