How to create conditional types in TypeScript ?
In this article, we will see how we create conditional types in TypeScript.
Taking a decision makes function useful for a different type of input. Conditional types, as the name suggests, define the types of value on the basis of conditions. Now, Conditional types seem like a conditional statement, although, it is same in the way that the conditional statement is used to choose the flow of code based on certain conditions and conditional types used for choosing different types for values.
Syntax: We can create the conditional types with the used of ternary operator and extends in TypeScript.
Type1 extends Type2 ? for One value : for different value;
Here extend works as compare function which checks is Type1 have properties of Type2 if yes then it jumps to true branch else in the false branch.
Now let’s understand through the following examples.
Example 1: In this example, we will create the Conditional types which take the values and check it has the property of number or not with extends. If it has the property of number conditional types assign the types to the caller of conditional type else it assigns never to types.
Example 2: Now, we will create the conditional type by narrowing the functionality of input data. In this type of creating conditional types, we will be filtering out the specific input type which contains some value. Here, we use extended function and set of values for narrowing with conditional types. First we will create the conditional types which checks the property if it is has a number string or Boolean or not then if it has
88 Hello Geeks true This is an error
Example 3: In this example first, we will create the conditional types for the number and string in one conditional type. After that, we use the same conditional types for both string and number.
88 Hey Geeks