0
0
Typescriptprogramming~30 mins

Conditional types for overload replacement in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Conditional Types for Overload Replacement in TypeScript
📖 Scenario: Imagine you are building a simple calculator function that can add numbers or concatenate strings. Instead of writing multiple overloads, you want to use TypeScript's conditional types to decide the return type based on the input type.
🎯 Goal: Create a function called combine that takes either two numbers or two strings. Use conditional types to make the return type number when inputs are numbers, and string when inputs are strings. Then test the function with both types.
📋 What You'll Learn
Create a generic type CombineResult<T> that uses conditional types to return number if T is number, otherwise string.
Write a function combine with two parameters a and b of the same generic type T.
Use the CombineResult<T> type as the return type of combine.
Inside combine, add numbers or concatenate strings based on the type of a.
Test combine with two numbers and two strings and print the results.
💡 Why This Matters
🌍 Real World
Conditional types help create flexible functions that adapt their return types based on input types, reducing the need for multiple overloads and making code easier to maintain.
💼 Career
Understanding conditional types is important for TypeScript developers to write clean, type-safe code that works well in large projects and libraries.
Progress0 / 4 steps
1
Create the generic conditional type
Create a generic type called CombineResult<T> that returns number if T is number, otherwise returns string.
Typescript
Need a hint?

Use T extends number ? number : string to create the conditional type.

2
Write the combine function signature
Write a generic function called combine with two parameters a and b of type T. Use CombineResult<T> as the return type.
Typescript
Need a hint?

Use function combine<T>(a: T, b: T): CombineResult<T> for the signature.

3
Implement the combine function logic
Inside the combine function, check if a is a number using typeof a === 'number'. If yes, return the sum of a and b. Otherwise, return the concatenation of a and b as strings.
Typescript
Need a hint?

Use typeof to check the type and cast the return value to CombineResult<T>.

4
Test the combine function and print results
Call combine with numbers 5 and 10 and store in resultNumber. Call combine with strings 'Hello' and 'World' and store in resultString. Print both results using console.log.
Typescript
Need a hint?

Use console.log(resultNumber) and console.log(resultString) to print the results.