0
0
Typescriptprogramming~20 mins

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

Choose your learning style9 modes available
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
1
Create the Shape interface
Create an interface called Shape with a name property of type string and an area method that returns a number.
Typescript
Need a hint?

Use the interface keyword to define the shape of an object.

2
Create the generic function with extends constraint
Create a generic function called printShapeInfo with a type parameter T that extends Shape. The function should accept a parameter shape of type T.
Typescript
Need a hint?

Use to restrict the generic type.

3
Print the shape's name and area inside the function
Inside the printShapeInfo function, write two console.log statements: one to print shape.name and another to print the result of shape.area().
Typescript
Need a hint?

Use template strings with console.log to show the values.

4
Create a circle object and call the function
Create a constant circle with name set to 'Circle' and an area method that returns 3.14 * 5 * 5. Then call printShapeInfo(circle).
Typescript
Need a hint?

Define circle as an object literal with the required properties and call the function.