DEV Community

Cover image for Master Typescript using Infer and Conditional types
Shashwat Nautiyal
Shashwat Nautiyal

Posted on • Updated on

Master Typescript using Infer and Conditional types

Become an expert in typescript using Infer and Conditional Types

What are infer and conditional types in TypeScript?

Conditional types in typescript can help when you want to select the type of different kinds conditionally. Infer keyword makes dependent type more flexible. It allows users to infer some sort as a whole or a part of that type which is very powerful in some cases.

How to use infer and conditional types?

The conditional type uses generics to pass the parameter constrained by a condition. The tertiary operator is used to select the type in the typescript if a condition is satisfied or not.

Typescript Conditional Type

Let us understand conditional types by an example 🧑🏻‍💻

type User = {
    name: string,
    email: string,
    followers: number,
    following: number,
    posts: number
}

type Admin = {
    name: string,
    email: string,
    isVarified: boolean,
    hasDbAccess: boolean,
}

type Profile<T extends "USER" | "ADMIN"> = {
    createdAt: Date,
    id: string
    type: T extends "USER" ? "user" : "admin",
    data: T extends "USER" ? User : Admin 
}

type UserProfile = Profile<"USER">
type AdminProfile = Profile<"ADMIN">
Enter fullscreen mode Exit fullscreen mode

Here we have created two types UserProfile and AdminProfile that is extracted from ProfileResponse<"USER" | "ADMIN">. Typescript automatically determines the param passed in the arrow parameter and adds property accordingly. Conditional types help to reduce the number of lines in your classes and reduce redundancy in your code.

Now let's checkout infer by an example ✍🏻

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

type GetFullName = InferPromise<Promise<{firstName: "groww", lastName: "tech"}>>

const getName = async () => {
    return Promise.resolve({
        name: "groww"
    })
}

type GetName = InferPromise<typeof getName>
Enter fullscreen mode Exit fullscreen mode

In the above example, we have created a InferPromise type that can infer the promise from the function or directly from the Promise class. The above example looks a little complex, but you do not have to worry. We will see another example.

type GetParamsAndReturn<T> = T extends (...args: infer P) => infer R
  ? { params: P; returnType: R }
  : never;

const getUser = (firstName: string, lastName: string, email: string, phone: string) => {

    return {
        name: firstName + lastName,
        email,
        phone,
        type: "user"
    }
}

type UserType = GetParamsAndReturn<typeof getUser>
type UserParams = UserType["params"];
type UserReturnType = UserType["returnType"]
Enter fullscreen mode Exit fullscreen mode

Here GetParamsAndReturn<T> can take any function and return the function parameters and return type. We can use this type to get any function's parameter and the return type.

Conclusion

In this article, we saw two of the advanced types in typescript. We also learned how we could use infer and conditional types in code. So, the next time you see the infer and conditional types, you will understand them properly.

Top comments (0)