How to create conditional types in TypeScript?
In TypeScript we need to define types for every variable and object as it is a strict language type and also contains conditional types.
From the word condition type, we can predict that we need to select a variable based on a specific condition. Yes, you heard it right. Just like we use if-else statements to execute a specific block of code based on specific conditions, we can also select the type of a variable based on specific conditions.
In this tutorial, we will learn to create conditional types in TypeScript.
grammar
Users can create conditional types in TypeScript according to the following syntax.
first_type extends second_type ? true_type : false_type;
We use the ternary operator in the above syntax to create conditional types.
Explanation of operands
First_type - It is a type or variable.
Second_type - It is a type like number, string, boolean etc.
True_type - If first_type contains second_type, true_type will be assigned to the variable.
False_type - If first_type does not extend second_type, false_type will be assigned to the variable.
Now we will look at different examples to learn more about conditional types in TypeScript.
Example
In the following example, we define two interfaces. In TypeScript, an interface also works the same as a type alias in that it defines the structure of an object or class.
After that, we extended interface2 with interface1. This means that interface2 contains all properties of interface1. After that, we assign the condition type to the type1 and type2 aliases using the ternary operator.
In the output, the user can check the types of var1 and var2 variables.
// Creating the first interface interface interface1 { prop1?: string; prop2: boolean; } // creating the second interface and extending it with the interface1 interface interface2 extends interface1 { prop3?: number; prop4: boolean; } // type of the type1 is number as interface2 extends interface1 type type1 = interface2 extends interface1 ? number : string; let var1: type1 = 20; // type of the type2 is string as interface1 doesn't extends the interface2 type type2 = interface1 extends interface2 ? number : string; let var2: type2 = "Hello"; console.log("The type of var1 variable is " + typeof var1); console.log("The type of var2 variable is " + typeof var2);
When compiled, it will generate the following JavaScript code -
var var1 = 20; var var2 = "Hello"; console.log("The type of var1 variable is " + typeof var1); console.log("The type of var2 variable is " + typeof var2);
Output
The above code will produce the following output -
The type of var1 variable is number The type of var2 variable is string
We have learned the basics of conditional types and how to create it.
Why use conditional types?
We will look at why and how conditional types are useful in real-world development.
Let’s take a look at the following code where we overload the func1() function by changing its return type based on the parameter types. We can observe that if the parameter type is boolean, the return type is string. Additionally, if the parameter types are string and number, the return types are number and boolean respectively.
function func1(param1: boolean): string; function func1(param1: string): number; function func1(param1: number): boolean; function func1(param1: any): any { // function body of the overloaded function }
We can overload this function by creating a conditional type with one definition in one line instead of writing multiple definitions in the function.
Example
In the following example, we create a condition type named test_type. It gets the value and returns the type based on the value type. If the value's type is a number, it returns a Boolean value; for a string value, it returns a number, and for a Boolean value, it returns the string type.
In the output, we can observe the variable obtained from test_type and the type of abc variable.
// creating the conditional type // it will accept the number, string, and boolean values type test_type<T extends number | string | boolean> = T extends number ? boolean : T extends string ? number : string; // getting the type of abc variable based on the value from the conditional test_type let abc: test_type<"hello"> = 20; console.log("The type of the variable abc is " + typeof abc); let variable: test_type<typeof abc> = false; console.log("The type of the variable is " + typeof variable);
When compiled, it will generate the following JavaScript code:
// getting the type of abc variable based on the value from the conditional test_type var abc = 20; console.log("The type of the variable abc is " + typeof abc); var variable = false; console.log("The type of the variable is " + typeof variable);
Output
The above code will produce the following output -
The type of the variable abc is number The type of the variable is boolean
Since we have used conditional types for variables, we can use them for function parameters or return types.
Users in this tutorial learned to create conditional types that allow us to select a specific variable based on the type or value of another variable. Additionally, we learned how to use conditional types for function parameters and return types.
The above is the detailed content of How to create conditional types in TypeScript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
