0
0
Typescriptprogramming~10 mins

Truthiness narrowing in Typescript - Interactive Code Practice

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

Complete the code to check if the variable value is truthy.

Typescript
if ([1]) {
  console.log("Value is truthy");
}
Drag options to blanks, or click blank then click option'
Avalue == null
B!value
Cvalue === false
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using negation like !value instead of value
Checking equality with false instead of truthiness
2fill in blank
medium

Complete the code to narrow the type by checking if input is truthy before accessing its property.

Typescript
function printLength(input: string | null) {
  if ([1]) {
    console.log(input.length);
  }
}
Drag options to blanks, or click blank then click option'
Ainput.length > 0
Binput
Cinput === null
Dinput === undefined
Attempts:
3 left
💡 Hint
Common Mistakes
Checking input === null which is true only when input is null
Checking input.length > 0 without ensuring input is not null
3fill in blank
hard

Fix the error by completing the condition to narrow data to a truthy value before accessing data.value.

Typescript
function process(data: { value: number } | null) {
  if ([1]) {
    console.log(data.value);
  }
}
Drag options to blanks, or click blank then click option'
Adata !== null
Bdata.value !== null
Cdata.value > 0
Ddata === undefined
Attempts:
3 left
💡 Hint
Common Mistakes
Checking data.value !== null causes error if data is null
Checking data === undefined misses the null case
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths only for words longer than 3 characters.

Typescript
const words = ["apple", "cat", "banana", "dog"];
const lengths = { [1]: [2] for (const word of words) if (word.length > 3) };
Drag options to blanks, or click blank then click option'
Aword
Bword.length
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping keys and values
Using word.length as key which is a number
5fill in blank
hard

Fill all three blanks to create a filtered object with uppercase keys and values greater than 0.

Typescript
const data = { a: 1, b: 0, c: 3 };
const filtered = { [1]: [2] for (const [[3], v] of Object.entries(data)) if (v > 0) };
Drag options to blanks, or click blank then click option'
Ak.toUpperCase()
Bv
Ck
Dv.toString()
Attempts:
3 left
💡 Hint
Common Mistakes
Using v as the key variable
Not converting keys to uppercase
Using v.toString() instead of v