0
0
Typescriptprogramming~10 mins

Function overloads 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 function overload for a function named combine that takes two numbers and returns a number.

Typescript
function combine(a: number, b: number): [1];
Drag options to blanks, or click blank then click option'
Anumber
Bvoid
Cboolean
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using string as return type when inputs are numbers.
Leaving the return type as void.
2fill in blank
medium

Complete the code to declare a function overload for combine that takes two strings and returns a string.

Typescript
function combine(a: string, b: string): [1];
Drag options to blanks, or click blank then click option'
Aboolean
Bnumber
Cstring
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using number as return type for string inputs.
Using any unnecessarily.
3fill in blank
hard

Fix the error in the implementation signature of the overloaded function combine.

Typescript
function combine(a: [1], b: [1]): [1] {
  if (typeof a === 'string' && typeof b === 'string') {
    return a + b;
  }
  return a + b;
}
Drag options to blanks, or click blank then click option'
Anumber
Bany
Cstring
Dunknown
Attempts:
3 left
💡 Hint
Common Mistakes
Using string or number only, which causes type errors.
Using unknown without type checks.
4fill in blank
hard

Fill both blanks to complete the function overloads for combine that accept either two numbers or two strings.

Typescript
function combine(a: [1], b: [1]): [1];
function combine(a: [2], b: [2]): [2];
Drag options to blanks, or click blank then click option'
Anumber
Bstring
Cboolean
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing parameter and return types incorrectly.
Using any in overload declarations.
5fill in blank
hard

Fill all three blanks to complete the overloaded function combine with implementation that handles both numbers and strings.

Typescript
function combine(a: [1], b: [1]): [2];
function combine(a: [3], b: [3]): [3];
function combine(a: any, b: any): any {
  if (typeof a === 'string' && typeof b === 'string') {
    return a + b;
  }
  return a + b;
}
Drag options to blanks, or click blank then click option'
Anumber
Bstring
Cany
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Using any in overload declarations instead of specific types.
Mismatching parameter and return types.