0
0
Typescriptprogramming~10 mins

Unknown type vs any type in Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a variable with the unknown type.

Typescript
let value: [1];
Drag options to blanks, or click blank then click option'
Aunknown
Bany
Cvoid
Dnever
Attempts:
3 left
💡 Hint
Common Mistakes
Using any instead of unknown disables type safety.
Confusing void with unknown.
2fill in blank
medium

Complete the code to assign a value of type unknown to a variable.

Typescript
let data: unknown = [1];
Drag options to blanks, or click blank then click option'
Atrue
B'hello'
C42
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to assign a value that is not valid syntax.
Confusing unknown with any in assignment.
3fill in blank
hard

Fix the error in the code by adding a type check before assignment.

Typescript
let value: string;
let input: unknown = 'test';
if (typeof input === [1]) {
  value = input;
}
Drag options to blanks, or click blank then click option'
A'number'
B'object'
C'boolean'
D'string'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning unknown directly without type check.
Using wrong type string in the check.
4fill in blank
hard

Fill both blanks to safely assign an unknown value to a number variable.

Typescript
let num: number;
let val: unknown = 10;
if (typeof val === [1]) {
  num = val [2] 0;
}
Drag options to blanks, or click blank then click option'
A'number'
B+
C-
D'string'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong type string in the check.
Missing arithmetic operation causing type errors.
5fill in blank
hard

Fill all three blanks to convert an any type to a string safely.

Typescript
let input: any = 123;
let output: string;
if (typeof input === [1]) {
  output = input [2] '';
} else {
  output = String([3]);
}
Drag options to blanks, or click blank then click option'
A'string'
B+
Cinput
Dinput.toString()
Attempts:
3 left
💡 Hint
Common Mistakes
Not checking type before assignment.
Using wrong conversion method.