Conditional types let you choose one type or another based on a condition. It helps make your code smarter and safer.
0
0
Conditional type syntax in Typescript
Introduction
When you want a type to change depending on another type.
When you want to create flexible functions that work with different types.
When you want to check if a type has a certain property or shape.
When you want to simplify complex type logic in your code.
Syntax
Typescript
type ResultType<T> = T extends SomeType ? TypeIfTrue : TypeIfFalse;The extends keyword here means 'if T fits into SomeType'.
If the condition is true, the type becomes TypeIfTrue, otherwise TypeIfFalse.
Examples
This checks if
T is a string. If yes, the type is "Yes", else "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, else T itself.Typescript
type ElementType<T> = T extends (infer U)[] ? U : T;This removes
null and undefined from a type.Typescript
type NonNullable<T> = T extends null | undefined ? never : T;
Sample Program
This program defines a conditional type CheckType that returns "Number" if the type is number, otherwise "Other". Then it shows how to use it with variables and prints the results.
Typescript
type CheckType<T> = T extends number ? "Number" : "Other"; let a: CheckType<number> = "Number"; let b: CheckType<string> = "Other"; console.log(a); console.log(b);
OutputSuccess
Important Notes
Conditional types are checked at compile time, so they don't affect runtime performance.
You can combine conditional types with other TypeScript features like infer to extract types.
Summary
Conditional types let you pick types based on conditions.
They use extends with a question mark and colon to choose between two types.
They help make your code flexible and safe by adapting types automatically.