Commit No Bug
Published on

Learning TypeScript: Conditional Types Unleashed

Authors
  • avatar
    Name
    nikUnique
    Twitter
An image about conditional types in TypeScript

I am learning TypeScript, and today I want to explain to you about conditional types and why they are useful. The first question is: What are conditional types in TypeScript? First, let's remember the ternary operator in vanilla JS.

const age = 20;
const canDrink = age >= 18 ? "Yes, you can drink" : "No, you're too young";

console.log(canDrink); // "Yes, you can drink"

Conditional types in TypeScript are similar to the ternary operator in JS, but the difference is that the result of using it will be a type, and not any value, like a string, for example. Also, one more difference is that it runs at compile time, while the ternary operator in JS runs at runtime, or in other words, when the code gets executed.

Conditional types are extensively used in popular TypeScript libraries for powerful, generic utilities. They enable inference and type safety in highly reusable scenarios (e.g., extracting types from functions or components). Here are real examples based on the built-in utility types in TypeScript's standard library. I will show the code and explain why conditionals are quite useful.

TypeScript Built-in: ReturnType<T> (From lib.es5.d.ts)

This helps to extract the return type of a function.

// From TypeScript source
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never

In the code above on the right side of the equal sign, with this T extends (...args: any[]) code we check whether we got any function with any number of parameters and any kind of types, and as long as a function is passed, the infer keyword helps us to extract the return type of a function. And if the condition is false, meaning that it isn't a function that is passed in, but for example a string or a number, then it will be the never type as a result of using the ReturnType<T> utility.

Usage:

function greet() {
  return 'hello'
}

type Greeting = ReturnType<typeof greet> // string

You can read more on the ReturnType<T> in TypeScript documentation.

Why to use conditional here: It infers R, the return type, from the function signature at compile time. And what if we pass not a function to the ReturnType<T>, but something else? Then we would have the never type as a result of such usage of the generic utility.

TypeScript Built-in: Parameters<T> (From lib.es5.d.ts)

This utility helps to extract a parameter tuple from a function.

type Parameters<T> = T extends (...args: infer P) => any[] ? P : never

Here is how to use it:

function add(a: number, b: number) {
  return a + b
}

type AddParams = Parameters<typeof add> // [number, number];

Why use conditional here? We get the type of every element in the parameter list, or in other words, the parameter tuple.

You can read more on the ParametersType<T> in TypeScript documentation.

In many cases, you may not need to use conditionals. But the above are 2 examples where conditionals nicely fit into the picture.

Here you have it! These examples are based on the built-in utility types in TypeScript's standard library, from which we can see that conditionals are useful.

Also, I built some stuff over the course of my learning programming, so here is what I have:

The PomoSimple Timer

The PomoSimple Timer is a web app designed for enhancing productivity by focusing on a task for short periods. I personally use it to learn programming; it is simple, yet has a timer history, which you can export via the csv format and other helpful features as well. Here is the link to the blog post I made about it; you can check it if you are interested. The link to the app itself is in the blog post.

The Voice Timer Android App

The Voice Timer app is a flexible timer app designed for hands-free control. I use it personally for my training, it is easier to just control timers with voice than with hands, and if it happens that I do not use it for my training for some reason, I miss my "Voice Timer" app. Here is the link to the blog post I made about it; you can check it if you are interested. The link to the app itself is in the blog post.

The Sea Battle Game

In the "Sea Battle" game, you can play against a computer in a sea battle game. Based on my assumptions, in a game where the first to win 3 times is the winner, players would lose to the bot over 90% of the time. Interested? Here is the link to the blog post I made about it. The link to the game itself is in the blog post.

Got questions? Send me an email to commitnobug@outlook.com.