typescript
/

TypeScript Conditional Types

Last Sync: Today

On this page

9
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

typescript

TypeScript Conditional Types

What are Conditional Types?

Conditional types allow you to define types based on conditions using the extends keyword, similar to if-else logic.

Basic Syntax

TypeScriptRead-only
1
type IsString<T> = T extends string ? true : false;

Example Usage

TypeScriptRead-only
1
type A = IsString<string>; // true
type B = IsString<number>; // false

Using infer Keyword

TypeScriptRead-only
1
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

Conditional with Union

TypeScriptRead-only
1
type ToArray<T> = T extends any ? T[] : never;

Nested Conditions

TypeScriptRead-only
1
type TypeName<T> =
  T extends string ? 'string' :
  T extends number ? 'number' :
  'other';

Best Practices

  • Use conditional types for dynamic typing
  • Keep conditions simple
  • Use infer for extracting types
  • Avoid overly complex nested conditions

Common Mistakes

  • Overcomplicating conditional logic
  • Misusing infer keyword
  • Ignoring readability
  • Incorrect type conditions

Conclusion

Conditional types provide powerful flexibility in TypeScript, enabling dynamic and reusable type logic.

Try it yourself

type IsString<T> = T extends string ? true : false;

Test Your Knowledge

Q1
of 3

Conditional uses?

A
if
B
extends
C
switch
D
case
Q2
of 3

infer used for?

A
Assign
B
Extract
C
Delete
D
Create
Q3
of 3

Condition returns?

A
Value
B
Type
C
Function
D
Object

Frequently Asked Questions

What is conditional type?

A type based on condition.

Keyword used?

extends.

What is infer?

Extracts types dynamically.

Previous

ts mapped types

Next

ts modules

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.