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.