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 stringCreate a generic class called
ItemHolder with a type parameter constrained to NamedAdd a constructor to
ItemHolder that accepts an item of the generic typeAdd a method
getName that returns the name of the stored itemCreate an object with a
name property and use ItemHolder to hold itPrint 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