Learn TypeScript
Creating a basic conditional type
Creating a basic conditional type
In this lesson, we will learn what conditional types are and how to create them.
Understanding conditional types
Types that we create can have conditional logic, just like regular JavaScript code.
T1 extends T2 ? A : B
The conditional type syntax uses the ternary operator that we are familiar with from JavaScript code.
The extends
keyword is used to define the condition. If T2
is within T1
then type A
is used; otherwise, type B
is used.
In the example below, Example1
resolves to string
:
type Person = { name: string; age: number;};type Example1 = Person extends {} ? string : number;
Conditional types aren't very useful on their own but are extremely useful in generic types. A common use case is to use a conditional type with the never
type to prune values from a type.
An example
We are going to create a conditional type in the code editor below:
The code contains a type that can be a string or null
, and this is used in a firstName
variable.
- Let's start to create a type alias for a generic type called
RemoveNull
:
type RemoveNull<T> =
- We want to remove
null
from the type. So, our condition will check whether the type containsnull
:
type RemoveNull<T> = T extends null;
- When this condition is
true
, we don't want to use that part of the type because we want to removenull
from it. We can use thenever
type for this:
type RemoveNull<T> = T extends null ? never;
- When this condition is
false
, we do want to use that part of the type, so we can just returnT
:
type RemoveNull<T> = T extends null ? never : T;
- Change the type of
firstName
to useRemoveNull
as follows:
let firstName: RemoveNull<NullableString>;
A type error now occurs where firstName
is assigned to null
. Why is this so?.
Nice!
We have just created a very similar type to a standard utility type called NonNullable
. The definition of NonNullable
is below:
type NonNullable<T> = T extends null | undefined ? never : T;
What is the difference (apart from the name) between RemoveNull
and NonNullable
?.
Summary
With the help of generics and the never
type, conditional types allow utility types to be created that remove possible values from a type. This approach is heavily used within Typescript's standard utility types.
In the next lesson, we will learn how to infer a type within a generic conditional type.