0
0
Typescriptprogramming~10 mins

Why typed functions matter 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 function that adds two numbers and returns a number.

Typescript
function add(a: number, b: number): [1] {
  return a + b;
}
Drag options to blanks, or click blank then click option'
Aboolean
Bstring
Cnumber
Dvoid
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' or 'void' as return type causes errors.
2fill in blank
medium

Complete the code to declare a function that takes a string and returns its length as a number.

Typescript
function getLength(text: string): [1] {
  return text.length;
}
Drag options to blanks, or click blank then click option'
Astring
Bvoid
Cboolean
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 'string' or 'void' causes type errors.
3fill in blank
hard

Fix the error in the function by specifying the correct return type.

Typescript
function isEven(num: number): [1] {
  return num % 2 === 0;
}
Drag options to blanks, or click blank then click option'
Aboolean
Bstring
Cnumber
Dvoid
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'number' or 'string' as return type causes errors.
4fill in blank
hard

Fill both blanks to declare a function that takes an array of numbers and returns the sum as a number.

Typescript
function sumArray(arr: [1]): [2] {
  return arr.reduce((acc, val) => acc + val, 0);
}
Drag options to blanks, or click blank then click option'
Anumber[]
Bstring[]
Cnumber
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string[]' or 'boolean' for the array or return type causes errors.
5fill in blank
hard

Fill all three blanks to declare a function that takes a string and a number, and returns a string repeated that many times.

Typescript
function repeatText(text: [1], times: [2]): [3] {
  return text.repeat(times);
}
Drag options to blanks, or click blank then click option'
Astring
Bnumber
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up parameter types or return type causes errors.