0
0
Typescriptprogramming~7 mins

Conditional type with generics in Typescript

Choose your learning style9 modes available
Introduction

Conditional types with generics let you choose a type based on a condition. This helps make your code flexible and safe.

When you want a function or type to return different types depending on input types.
When you want to create reusable components that adapt their types automatically.
When you want to enforce rules on types based on other types in your code.
Syntax
Typescript
type MyType<T> = T extends Condition ? TrueType : FalseType;

The T extends Condition checks if T fits the condition.

If yes, it uses TrueType, otherwise FalseType.

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. If T is an array, it returns the element type; otherwise, it returns T itself.
Typescript
type ElementType<T> = T extends (infer U)[] ? U : T;
Sample Program

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

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

// Test with number
const test1: IsNumber<number> = "Number";

// Test with string
const test2: IsNumber<string> = "Not Number";

console.log(test1);
console.log(test2);
OutputSuccess
Important Notes

Conditional types work at compile time to help TypeScript understand your code better.

You can combine conditional types with generics to create very flexible and reusable types.

Summary

Conditional types choose one type or another based on a condition.

Generics let you write flexible code that works with many types.

Together, they help create smart, adaptable type definitions.