Generic constraints with extends
📖 Scenario: Imagine you are building a small program to handle different types of shapes. Each shape has a name and a method to calculate its area. You want to write a function that can accept any shape but only if it has these properties.
🎯 Goal: Build a TypeScript function using generics with extends to accept only objects that have a name string and an area method returning a number.
📋 What You'll Learn
Create an interface called
Shape with a name property of type string and an area method returning number.Create a generic function called
printShapeInfo that accepts a parameter T constrained to Shape using extends.Inside the function, print the shape's
name and the result of calling its area method.Create an object
circle with name as 'Circle' and an area method returning 3.14 * radius * radius where radius is 5.Call
printShapeInfo with the circle object.💡 Why This Matters
🌍 Real World
Using generic constraints helps ensure functions only accept objects with the right shape, preventing errors and making code easier to understand.
💼 Career
Many programming jobs require writing reusable and safe code. Understanding generics with constraints is key for working with TypeScript and other typed languages.
Progress0 / 4 steps