0
0
Typescriptprogramming~20 mins

Function overloads in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Function overloads
📖 Scenario: You are building a simple calculator that can add numbers or concatenate strings. Depending on the input types, the calculator should behave differently.
🎯 Goal: Create a TypeScript function called combine that works with both numbers and strings using function overloads. It should add numbers or join strings.
📋 What You'll Learn
Create two function overload signatures for combine: one for two numbers, one for two strings
Implement the combine function to handle both cases
Test the function by calling combine with numbers and strings
Print the results of the function calls
💡 Why This Matters
🌍 Real World
Function overloads help create flexible functions that work with different types of inputs, like calculators or formatters.
💼 Career
Many programming jobs require writing clean, reusable code that handles multiple data types safely, especially in TypeScript.
Progress0 / 4 steps
1
Create function overload signatures
Write two function overload signatures for a function called combine. The first signature takes two number parameters and returns a number. The second signature takes two string parameters and returns a string.
Typescript
Need a hint?

Function overloads are multiple function declarations with the same name but different parameter types.

2
Implement the combine function
Implement the combine function with parameters a and b of type any. Inside the function, check if both a and b are numbers and return their sum. Otherwise, return their concatenation as strings.
Typescript
Need a hint?

Use typeof to check the types inside the function and return accordingly.

3
Call the combine function with numbers and strings
Call the combine function twice: once with numbers 5 and 10, and once with strings 'Hello' and 'World'. Store the results in variables called resultNumbers and resultStrings respectively.
Typescript
Need a hint?

Call the function with exact values and store the results in variables.

4
Print the results
Print the values of resultNumbers and resultStrings using two separate console.log statements.
Typescript
Need a hint?

Use console.log to show the results on the screen.