Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a variable with a safe type.
Typescript
let userName: [1] = "Alice";
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'any' type which disables safety checks.
✗ Incorrect
Using string ensures the variable only holds text, which is safer than any.
2fill in blank
mediumComplete the code to define a function parameter with a safe type.
Typescript
function greet(name: [1]) { console.log(`Hello, ${name}!`); } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'any' which can cause unexpected errors.
✗ Incorrect
Defining the parameter as string ensures only text is accepted, preventing errors.
3fill in blank
hardFix the error by choosing the correct type for the variable.
Typescript
let age: [1] = "30";
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'number' type with a string value causes errors.
✗ Incorrect
The value is a string, so the type must be string to avoid type errors.
4fill in blank
hardFill both blanks to create a safe object type and assign it.
Typescript
type User = { name: [1]; age: [2]; };
const user: User = { name: "Bob", age: 25 }; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing types or using 'any' reduces safety.
✗ Incorrect
The name should be string and age should be number for type safety.
5fill in blank
hardFill all three blanks to safely check a variable's type before using it.
Typescript
function printAge(age: [1] | [2]) { if (typeof age === [3]) { console.log(`Age is ${age}`); } else { console.log("Invalid age"); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using type names instead of string literals in typeof check.
✗ Incorrect
The function accepts number or string. The typeof check must compare to the string "string" to be correct.