0
0
Typescriptprogramming~15 mins

The any type and why to avoid it in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
The any type and why to avoid it
📖 Scenario: Imagine you are building a simple app that stores information about fruits and their colors. You want to keep your data safe and clear so you can avoid mistakes later.
🎯 Goal: You will create a variable with the any type, then replace it with a proper type to see why avoiding any helps keep your code safe and easy to understand.
📋 What You'll Learn
Create a variable called fruit with type any and assign it an object with name and color properties.
Create a type called Fruit with name and color as string properties.
Change the fruit variable to use the Fruit type instead of any.
Try to assign a wrong type to fruit and observe the error.
Print the fruit variable to show its content.
💡 Why This Matters
🌍 Real World
In real apps, using specific types helps avoid bugs and makes code easier to fix and improve.
💼 Career
Many jobs require writing clear and safe TypeScript code without relying on <code>any</code> to keep projects reliable.
Progress0 / 4 steps
1
Create a variable with the any type
Create a variable called fruit with type any and assign it an object with name set to "Apple" and color set to "Red".
Typescript
Need a hint?

Use let fruit: any = { name: "Apple", color: "Red" };

2
Create a type for the fruit object
Create a type called Fruit with two string properties: name and color.
Typescript
Need a hint?

Use type Fruit = { name: string; color: string; };

3
Use the Fruit type instead of any
Change the variable fruit to use the Fruit type instead of any.
Typescript
Need a hint?

Change let fruit: any to let fruit: Fruit

4
Print the fruit variable
Write a console.log statement to print the fruit variable.
Typescript
Need a hint?

Use console.log(fruit); to show the fruit object.