0
0
Typescriptprogramming~5 mins

Why conditional types are needed in Typescript

Choose your learning style9 modes available
Introduction

Conditional types help TypeScript choose different types based on conditions. This makes your code smarter and safer by adapting types automatically.

When you want a type to change depending on another type.
When you need to create flexible functions that work with many types but behave differently.
When you want to check if a type has a certain property and act accordingly.
When you want to build reusable components that adapt their types based on input.
When you want to avoid writing many similar types by combining them with conditions.
Syntax
Typescript
type Name<T> = T extends U ? X : Y;

T is the type you check.

If T fits U, then the type becomes X, otherwise Y.

Examples
This type returns "Yes" if T is a string, otherwise "No".
Typescript
type IsString<T> = T extends string ? "Yes" : "No";
This extracts the type inside an array, or returns T if it is not an array.
Typescript
type ElementType<T> = T extends (infer U)[] ? U : T;
Sample Program

This program defines a conditional type that checks if a type is number. It then uses it with number and string types and prints the results.

Typescript
type IsNumber<T> = T extends number ? "Number" : "Not Number";

// Test with number
let a: IsNumber<number> = "Number";
// Test with string
let b: IsNumber<string> = "Not Number";

console.log(a);
console.log(b);
OutputSuccess
Important Notes

Conditional types let TypeScript pick types based on logic, making your code more flexible.

They work well with generics to create smart reusable code.

Summary

Conditional types choose types based on conditions.

They help write flexible and safe code.

Use them to adapt types automatically depending on input.