0
0
Typescriptprogramming~10 mins

Union type syntax and behavior 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 declare a variable that can hold a string or a number.

Typescript
let value: [1];
Drag options to blanks, or click blank then click option'
Astring, number
Bstring & number
Cstring | number
Dstring number
Attempts:
3 left
💡 Hint
Common Mistakes
Using a comma instead of a pipe to separate types.
Using an ampersand (&) which means intersection, not union.
2fill in blank
medium

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

Typescript
function printNames(names: [1]) {
  if (typeof names === 'string') {
    console.log(names);
  } else {
    names.forEach(name => console.log(name));
  }
}
Drag options to blanks, or click blank then click option'
Astring & string[]
Bstring string[]
Cstring, string[]
Dstring | string[]
Attempts:
3 left
💡 Hint
Common Mistakes
Using an ampersand (&) which means intersection, not union.
Separating types with a comma instead of a pipe.
3fill in blank
hard

Fix the error in the union type declaration for the variable.

Typescript
let data: [1] = 42;
Drag options to blanks, or click blank then click option'
Anumber | string
Bnumber & string
Cnumber, string
Dnumber string
Attempts:
3 left
💡 Hint
Common Mistakes
Using intersection (&) instead of union (|).
Using commas or spaces instead of pipes.
4fill in blank
hard

Fill both blanks to create a union type and check the type inside the function.

Typescript
function process(input: [1]) {
  if (typeof input === [2]) {
    console.log('Input is a string:', input);
  }
}
Drag options to blanks, or click blank then click option'
Astring | number
B'string'
C'number'
Dstring & number
Attempts:
3 left
💡 Hint
Common Mistakes
Using intersection (&) instead of union (|).
Checking typeof against a type name without quotes.
5fill in blank
hard

Fill all three blanks to create a union type, check the type, and handle both cases.

Typescript
function format(value: [1]) {
  switch (typeof value) {
    case [2]:
      return value.toUpperCase();
    case [3]:
      return value.toFixed(2);
  }
}
Drag options to blanks, or click blank then click option'
Astring | number
B'string'
C'number'
D'boolean'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong type literals in switch cases.
Not using union type for the parameter.