0
0
Typescriptprogramming~15 mins

Conditional type syntax in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Conditional type syntax
📖 Scenario: Imagine you are building a simple TypeScript program that decides the type of a variable based on a condition. This is useful when you want your code to be flexible and safe at the same time.
🎯 Goal: You will create a conditional type that checks if a type is string. If it is, the type will become number, otherwise it will become boolean. Then you will use this conditional type with different example types and print the results.
📋 What You'll Learn
Create a conditional type called TypeCheck that checks if a generic type T extends string.
If T extends string, TypeCheck<T> should be number.
Otherwise, TypeCheck<T> should be boolean.
Create two variables: result1 with type TypeCheck<string> and result2 with type TypeCheck<number>.
Assign 42 to result1 and true to result2.
Print result1 and result2 to the console.
💡 Why This Matters
🌍 Real World
Conditional types help developers write code that changes behavior based on types, making libraries and applications more flexible and safer.
💼 Career
Understanding conditional types is important for TypeScript developers working on large codebases or libraries where type safety and flexibility are critical.
Progress0 / 4 steps
1
Create the conditional type
Create a conditional type called TypeCheck that takes a generic type T. Use the syntax T extends string ? number : boolean to define it.
Typescript
Need a hint?

Use the extends keyword inside the type definition to check the condition.

2
Create variables using the conditional type
Create a variable called result1 with type TypeCheck<string> and assign it the value 42. Then create a variable called result2 with type TypeCheck<number> and assign it the value true.
Typescript
Need a hint?

Remember to specify the type of each variable using TypeCheck with the correct generic type.

3
Add a function to display the results
Create a function called displayResults that takes two parameters: a of type number and b of type boolean. Inside the function, use console.log to print both values with labels.
Typescript
Need a hint?

Use console.log twice to print both values with clear labels.

4
Call the function to show the output
Call the function displayResults with result1 and result2 as arguments to print their values.
Typescript
Need a hint?

Call displayResults with the two variables you created.