0
0
Typescriptprogramming~15 mins

Unknown type vs any type in Typescript - Hands-On Comparison

Choose your learning style9 modes available
Unknown type vs any type
📖 Scenario: Imagine you are building a simple TypeScript program that processes user input. Sometimes you don't know the exact type of the input, so you need to handle it carefully.
🎯 Goal: You will learn the difference between the unknown type and the any type in TypeScript by creating variables with these types and safely working with them.
📋 What You'll Learn
Create variables with unknown and any types
Add a type check before using the unknown variable
Assign values to both variables
Print the results to see how TypeScript treats them
💡 Why This Matters
🌍 Real World
In real projects, you often get data from unknown sources like user input or APIs. Using <code>unknown</code> helps you check data before using it, preventing bugs.
💼 Career
Understanding <code>unknown</code> and <code>any</code> types is important for writing safe TypeScript code, a valuable skill for frontend and backend developers.
Progress0 / 4 steps
1
Create variables with unknown and any types
Create a variable called valueUnknown with type unknown and a variable called valueAny with type any. Assign the number 10 to both variables.
Typescript
Need a hint?

Use let to declare variables and specify the types unknown and any explicitly.

2
Add a type check for the unknown variable
Add an if statement to check if valueUnknown is a number before assigning it to a new variable called numFromUnknown.
Typescript
Need a hint?

Use typeof to check the type before assigning valueUnknown to numFromUnknown.

3
Assign valueAny to a new variable without type check
Assign valueAny directly to a new variable called numFromAny without any type check.
Typescript
Need a hint?

You can assign valueAny directly without checking its type.

4
Print the results
Print numFromUnknown and numFromAny using console.log to see their values.
Typescript
Need a hint?

Use console.log to print both variables on separate lines.