0
0
Typescriptprogramming~15 mins

Why conditional types are needed in Typescript - See It in Action

Choose your learning style9 modes available
Why conditional types are needed
📖 Scenario: Imagine you are building a simple TypeScript program that handles different types of user inputs. Sometimes the input is a string, and sometimes it is a number. You want your program to respond differently depending on the input type.
🎯 Goal: You will create a conditional type that checks if a type is string or number and returns a different message type accordingly. This will help you understand why conditional types are useful in TypeScript.
📋 What You'll Learn
Create a type alias called InputType that can be either string or number.
Create a conditional type called ResponseType that returns 'You gave a string' if the input is string, and 'You gave a number' if the input is number.
Create a variable called input of type InputType and assign it the value 'hello'.
Create a variable called response of type ResponseType<typeof input>.
Print the value of response.
💡 Why This Matters
🌍 Real World
Conditional types help developers write flexible code that adapts to different data types automatically, reducing bugs and improving code clarity.
💼 Career
Understanding conditional types is important for TypeScript developers working on complex applications where data types can vary and need precise handling.
Progress0 / 4 steps
1
Create the input type
Create a type alias called InputType that can be either string or number.
Typescript
Need a hint?

Use the | symbol to combine types in TypeScript.

2
Create the conditional type
Create a conditional type called ResponseType that takes a generic type T and returns 'You gave a string' if T is string, otherwise returns 'You gave a number'.
Typescript
Need a hint?

Use the syntax T extends string ? X : Y to create a conditional type.

3
Create the input variable
Create a variable called input of type InputType and assign it the value 'hello'.
Typescript
Need a hint?

Use const input: InputType = 'hello'; to create the variable.

4
Create the response variable and print it
Create a variable called response of type ResponseType<typeof input> and assign it the value 'You gave a string'. Then print the value of response using console.log.
Typescript
Need a hint?

Use console.log(response); to print the message.