Conditional Types in TypeScript

Conditional types in TypeScript are types are created on the basis of a condition.

Structure

type nameOfType = aType extends anotherType ? TrueType : FalseType

What we are telling TypeScript is to create a new type called nameOfType based on evaluating the expression of whether aType is an extension or subset of anotherType. If that is true, then nameOfType becomes of type TrueType. Otherwise, it becomes FalseType.

Examples

type Vehicle = {
  make: string,
  model: string,
  typeOfVehicle: string,
}

type Car = {make: string}

type CarMake = Vehicle extends Car ? string : null; //type CarMake = string;

If we were to replace the property in Car with a property and data type that does not exist in Vehicle, we would get null:

type Vehicle = {
  make: string,
  model: string,
  typeOfVehicle: string,
}

type Car = {year: number}

type CarMake = Vehicle extends Car ? string : null; //type CarMake = null;

We can also use conditional types with Generics:

type isBoolean<T> = T extends boolean ? true : false;

type isActive = boolean;

type userIsActive = isBoolean<isActive> //type userIsActive = true

This blog post was originally published on my blog Communicode, where I write about different tech topics.

TypeScript
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.