In this tutorial, we aim to understand and effectively use Conditional Types in TypeScript to make our code more flexible and adaptable to different conditions.
You'll learn what Conditional Types are, how to use them in your TypeScript code, and best practices to adopt while using them.
Basic knowledge of TypeScript is required. If you are new to TypeScript, you might want to familiarize yourself with it before diving into this tutorial.
Conditional types are a powerful feature in TypeScript that allows you to choose the type of a value based on a condition. They are defined using the T extends U ? X : Y
syntax, where T
and U
are types, and X
and Y
are the types to be used depending on whether T
extends U
.
Here's a simple example:
type IsString<T> = T extends string ? 'yes' : 'no';
In this example, IsString<T>
will be 'yes'
if T
is a string, and 'no'
otherwise.
When using conditional types, it's important to remember that they should not be used to replace regular logic, but to create more flexible and adaptable type definitions. It's also a good practice to use descriptive names for your types to make your code easier to understand.
type IsString<T> = T extends string ? 'yes' : 'no';
type SomeType = IsString<'hello'>; // 'yes'
type AnotherType = IsString<number>; // 'no'
In this example, SomeType
is 'yes'
because 'hello'
is a string, and AnotherType
is 'no'
because number
is not a string.
type NonNullable<T> = T extends null | undefined ? never : T;
type SomeType = NonNullable<string | null | undefined>; // string
In this example, NonNullable<T>
is used to exclude null
and undefined
from a type. SomeType
is string
because string | null | undefined
with null
and undefined
removed is string
.
In this tutorial, we've learned about conditional types in TypeScript and how to use them to make our code more flexible. We've also looked at some best practices and examples to help you get started.
For further learning, you can explore other TypeScript features like mapped types, union types, and intersection types. The TypeScript documentation is a great resource for this.
Create a conditional type IsNumber<T>
that is 'yes'
if T
is a number, and 'no'
otherwise.
type IsNumber<T> = T extends number ? 'yes' : 'no';
Create a conditional type ExcludeBoolean<T>
that excludes boolean
from T
.
type ExcludeBoolean<T> = T extends boolean ? never : T;
These exercises should give you a good understanding of how to use conditional types. For further practice, try to use conditional types in your own TypeScript projects.