Bird
Raised Fist0
Typescriptprogramming~10 mins

Unknown type vs any type in Typescript - Visual Side-by-Side Comparison

Choose your learning style10 modes available
Concept Flow - Unknown type vs any type
Declare variable with 'any'
↓
Assign any value
↓
Use variable freely
↓
No type checks
↓
Declare variable with 'unknown'
↓
Assign any value
↓
Use variable cautiously
↓
Type checks needed before use
Variables with 'any' accept all values and allow any operation without checks. Variables with 'unknown' accept all values but require type checks before use.
Execution Sample
Typescript
let a: any = 5;
let u: unknown = 5;

let b = a + 10;
// let c = u + 10; // Error

if (typeof u === 'number') {
  let c = u + 10;
}
Shows how 'any' allows operations freely, but 'unknown' requires a type check before using in operations.
Execution Table
StepVariableValue AssignedOperationResultNotes
1a5Declarationa = 5'any' accepts number 5
2u5Declarationu = 5'unknown' accepts number 5
3ba + 10Calculate b = a + 10b = 15'any' allows addition without error
4cu + 10Attempt c = u + 10Error'unknown' disallows operation without check
5typeof u === 'number'trueType checkPassCheck confirms u is number
6cu + 10Calculate c = u + 10c = 15After check, operation allowed
💡 Execution stops because 'unknown' type requires type check before operations; direct use causes error.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 6
aundefined5555
uundefinedundefined555
bundefinedundefinedundefined1515
cundefinedundefinedundefinedundefined15
Key Moments - 2 Insights
Why does adding 10 to 'a' work but adding 10 to 'u' causes an error?
'a' is typed as 'any', so TypeScript skips type checks and allows any operation (see step 3). 'u' is 'unknown', so TypeScript requires a type check before using it in operations (see step 4).
What must you do before using a variable of type 'unknown' in an operation?
You must check its type first, for example using 'typeof' (see step 5), to ensure it is safe to use in that operation.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'b' after step 3?
A15
BError
Cundefined
D5
💡 Hint
Check the 'Result' column for step 3 in the execution_table.
At which step does the type check for 'u' happen?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look for the row mentioning 'Type check' in the 'Operation' column.
If we remove the type check for 'u', what happens when we try 'u + 10'?
AIt works fine like 'any'
BTypeScript gives an error
CThe result is NaN
DThe code runs but warns at runtime
💡 Hint
Refer to step 4 where 'u + 10' without check causes an error.
Concept Snapshot
TypeScript 'any' type disables type checking and allows any operation.
'unknown' type accepts any value but requires type checks before use.
Use 'typeof' or other checks to safely use 'unknown'.
Avoid 'any' to keep type safety.
'unknown' is safer for unknown inputs.
Full Transcript
This visual execution compares TypeScript's 'any' and 'unknown' types. Variables declared with 'any' accept any value and allow any operation without errors or checks. Variables declared with 'unknown' also accept any value but require explicit type checks before using them in operations. The code example shows assigning 5 to both 'a' (any) and 'u' (unknown). Adding 10 to 'a' works immediately, but adding 10 to 'u' causes a compile error until a type check confirms 'u' is a number. The execution table traces each step, showing variable values and when errors occur. The variable tracker shows how values change after each step. Key moments clarify why 'unknown' needs checks and 'any' does not. The quiz tests understanding of these differences. The snapshot summarizes the main points: 'any' disables checks, 'unknown' requires checks, and 'unknown' is safer for unknown data.

Practice

(1/5)
1. What is the main difference between unknown and any types in TypeScript?
easy
A. unknown requires type checking before use, any does not.
B. any requires type checking before use, unknown does not.
C. unknown and any behave exactly the same.
D. any is safer than unknown.

Solution

  1. Step 1: Understand unknown behavior

    unknown means the value can be anything, but you must check its type before using it to avoid errors.
  2. Step 2: Understand any behavior

    any disables type checking, so you can use the value without checks, which can cause runtime errors.
  3. Final Answer:

    unknown requires type checking before use, any does not. -> Option A
  4. Quick Check:

    unknown = safe, any = unchecked [OK]
Hint: Remember: unknown forces checks, any skips them [OK]
Common Mistakes:
  • Thinking any is safer than unknown
  • Assuming unknown allows direct use without checks
  • Believing unknown and any behave the same
2. Which of the following is the correct way to assign a value of type unknown to a variable of type string?
easy
A. let a: unknown = "hello"; let b: string = a as string;
B. let a: unknown = "hello"; let b: string = a.toString();
C. let a: unknown = "hello"; let b: string = a + '';
D. let a: unknown = "hello"; let b: string = a;

Solution

  1. Step 1: Understand assignment rules for unknown

    You cannot assign unknown directly to a more specific type without a type assertion or check.
  2. Step 2: Check options for correct syntax

    let a: unknown = "hello"; let b: string = a as string; uses a type assertion as string, which is the correct way to tell TypeScript the value is a string.
  3. Final Answer:

    let b: string = a as string; -> Option A
  4. Quick Check:

    Use as to convert unknown safely [OK]
Hint: Use 'as' to convert unknown to a specific type [OK]
Common Mistakes:
  • Assigning unknown directly without assertion
  • Using incorrect type assertion syntax
  • Calling methods on unknown without checks
3. What will be the output of the following TypeScript code?
let value: unknown = 42;
if (typeof value === 'number') {
  console.log(value + 8);
} else {
  console.log('Not a number');
}
medium
A. TypeError at runtime
B. Not a number
C. 50
D. Compilation error

Solution

  1. Step 1: Check the type of value

    The variable value is unknown but assigned 42, a number.
  2. Step 2: Evaluate the if condition and output

    The condition typeof value === 'number' is true, so it logs value + 8 which is 42 + 8 = 50.
  3. Final Answer:

    50 -> Option C
  4. Quick Check:

    Type check passes, output is 50 [OK]
Hint: Check type before using unknown to avoid errors [OK]
Common Mistakes:
  • Assuming unknown can be used without type check
  • Expecting runtime error without type check
  • Confusing unknown with any behavior
4. Identify the error in this TypeScript code snippet:
let data: unknown = 'hello';
let length: number = data.length;
medium
A. No error, code runs fine.
B. Cannot access property 'length' on type 'unknown'.
C. Type 'string' is not assignable to type 'unknown'.
D. Variable 'length' should be type 'string'.

Solution

  1. Step 1: Understand property access on unknown

    You cannot access properties directly on a variable typed as unknown without type checking or assertion.
  2. Step 2: Identify the error message

    Trying to access data.length causes a compile-time error: "Cannot access property 'length' on type 'unknown'."
  3. Final Answer:

    Cannot access property 'length' on type 'unknown'. -> Option B
  4. Quick Check:

    Accessing unknown properties causes error [OK]
Hint: Check type before accessing unknown properties [OK]
Common Mistakes:
  • Assuming unknown behaves like any
  • Ignoring compiler error on property access
  • Wrongly typing variables
5. You receive data from an external API typed as any. You want to safely use it as a string only if it really is a string. Which approach is best?
hard
A. Assign the any data directly to a string variable.
B. Cast the any data to unknown and then to string without checks.
C. Ignore types and use the data as is.
D. Use a type guard to check if data is a string before using it.

Solution

  1. Step 1: Understand risks of any

    any disables type checking, so using it directly can cause runtime errors if the data is not as expected.
  2. Step 2: Use type guard for safety

    Checking the type with a type guard (e.g., typeof data === 'string') ensures safe usage only when the data is a string.
  3. Final Answer:

    Use a type guard to check if data is a string before using it. -> Option D
  4. Quick Check:

    Type guard ensures safe use of any data [OK]
Hint: Always check any data type before use [OK]
Common Mistakes:
  • Assigning any directly without checks
  • Casting any to unknown then string without validation
  • Ignoring type safety for external data
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard