📖 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
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
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
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
Hint
Use console.log(fruit); to show the fruit object.
Practice
(1/5)
1. What does the any type do in TypeScript?
easy
A. It converts the variable to a string.
B. It enforces strict type checking.
C. It automatically infers the variable type.
D. It disables type checking for the variable.
Solution
Step 1: Understand the role of any
The any type tells TypeScript to skip type checking for that variable.
Step 2: Compare with other types
Unlike specific types, any allows any value without errors or warnings.
Final Answer:
It disables type checking for the variable. -> Option D
Quick Check:
any disables type checking [OK]
Hint: Remember: any skips all type checks [OK]
Common Mistakes:
Thinking any enforces types
Confusing any with type inference
Assuming any converts types automatically
2. Which of the following is the correct way to declare a variable with the any type in TypeScript?