0
0
Typescriptprogramming~10 mins

Why union types are needed in Typescript - Test Your Understanding

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

Complete the code to declare a variable that can hold either a string or a number.

Typescript
let value: [1];
Drag options to blanks, or click blank then click option'
Astring
Bstring & number
Cstring | number
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using & instead of | which means intersection, not union.
Declaring only one type when both are needed.
2fill in blank
medium

Complete the function parameter type to accept either a string or an array of strings.

Typescript
function greet(names: [1]) {
  if (typeof names === 'string') {
    console.log(`Hello, ${names}!`);
  } else {
    names.forEach(name => console.log(`Hello, ${name}!`));
  }
}
Drag options to blanks, or click blank then click option'
Astring[]
Bany
Cstring & string[]
Dstring | string[]
Attempts:
3 left
💡 Hint
Common Mistakes
Using only string[] which excludes single strings.
Using intersection & which is incorrect here.
3fill in blank
hard

Fix the error in the type annotation to allow the variable to hold a number or null.

Typescript
let result: [1] = null;
Drag options to blanks, or click blank then click option'
Anull
Bnumber | null
Cnumber
Dnumber & null
Attempts:
3 left
💡 Hint
Common Mistakes
Using intersection & which causes a type error.
Not including null in the type.
4fill in blank
hard

Fill both blanks to create a function that returns either a string or undefined based on input.

Typescript
function getName(id: number): [1] {
  if (id === 1) {
    return 'Alice';
  }
  return [2];
}
Drag options to blanks, or click blank then click option'
Astring | undefined
Bnull
Cundefined
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Returning null instead of undefined.
Not using union type for the return type.
5fill in blank
hard

Fill all three blanks to create a variable that can hold a boolean, number, or string.

Typescript
let data: [1] = true;
data = 42;
data = [2];
data = [3];
Drag options to blanks, or click blank then click option'
Aboolean | number | string
B'hello'
C"world"
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Not including all types in the union.
Using wrong quotes for strings.