0
0
Typescriptprogramming~20 mins

Conditional type with generics in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Conditional type with generics
📖 Scenario: Imagine you are building a simple system that handles different types of user inputs. Sometimes the input is a string, and sometimes it is a number. You want to create a type that changes based on the input type to help your program understand what kind of data it is working with.
🎯 Goal: You will create a conditional type using generics in TypeScript that returns string if the input type is number, and returns number if the input type is string. Then, you will test this type with different inputs and print the results.
📋 What You'll Learn
Create a generic conditional type called SwapType that takes a type parameter T.
If T is number, SwapType<T> should be string.
If T is string, SwapType<T> should be number.
Create variables using SwapType with number and string to test the conditional type.
Print the values of these variables.
💡 Why This Matters
🌍 Real World
Conditional types with generics help create flexible and safe code that adapts to different data types automatically.
💼 Career
Understanding conditional types is important for TypeScript developers to write reusable and type-safe code in modern web applications.
Progress0 / 4 steps
1
Create the generic conditional type SwapType
Create a generic conditional type called SwapType that takes a type parameter T. It should return string if T is number, and number if T is string.
Typescript
Need a hint?

Use the syntax type SwapType<T> = T extends number ? string : number; to create the conditional type.

2
Create variables using SwapType with number and string
Create a variable called stringValue of type SwapType<number> and assign it the value "hello". Then create a variable called numberValue of type SwapType<string> and assign it the value 42.
Typescript
Need a hint?

Remember to use const stringValue: SwapType<number> = "hello"; and const numberValue: SwapType<string> = 42;.

3
Create a function to display the values
Create a function called displayValues that takes two parameters: val1 of type SwapType<number> and val2 of type SwapType<string>. Inside the function, create a string that combines both values separated by a comma and assign it to a variable called result.
Typescript
Need a hint?

Use a template string to combine val1 and val2 inside the function.

4
Print the combined result using displayValues
Call the function displayValues with stringValue and numberValue as arguments. Print the returned result using console.log.
Typescript
Need a hint?

Use console.log(displayValues(stringValue, numberValue)); to print the combined string.