Inferring Within Conditional Types
Inferring within conditional types in TypeScript is a technique that allows you to infer types within a conditional type definition. It’s a powerful way to create more precise and flexible type transformations. TypeScript introduced this capability in version 4.1, enhancing the expressiveness of conditional types.
Syntax
type ConditionalType<T> = T extends Condition ? (infer U) => void : Value 2;
Where-
- infer is a keyword which is used to create a new generic type variable named U
- Value2 will be the output whenever the condition is false.
Example: This examples we define a conditional type ConvertToStringOrNumber that transforms types based on a condition. We use this type within a function convertValue to dynamically convert input values to either strings or numbers based on their types. The examples showcase how the function’s conditional logic produces different runtime outputs when applied to strings and numbers.
Javascript
type ElementType<T> = T extends (infer U)[] ? U : never; const numbers: number[] = [1, 2, 3, 4, 5]; const strnumber: String[] = [ "1" , "3" , "7" ]; const element: ElementType< typeof numbers> = numbers[0]; // This is invalid it will give error const element2: ElementType< typeof numbers> = strnumber[0]; // Output: 1 console.log(element); |
Output:
TypeScript Conditional Types
In this article, we are going to discuss Conditional Types. Conditional types in TypeScript are a powerful feature that allows you to create types that depend on a condition or a set of conditions. As JavaScript is a loosely typed language, conditional types enable you to define types that are based on the values or the properties of other types. It uses the extend keyword and a to define a condition and then produce different types based on whether that condition is true or false. This takes a form that looks a little like conditional expressions (condition ? trueExpression: false expressions.
Syntax
type ConditionalType<T> = T extends Condition ? value 1: value 2;
Where-
- ConditionalType<T> is the name of the type having <T> type parameter.
- T extends Condition is the condition that will return true or false
- Value1 is the value when the condition will be true.
Example: In this example, We define a conditional type Num<T> that checks whether the given type T is an array of numbers, an array of strings, or neither, and returns either number, string, or never accordingly. It then uses this conditional type to declare variables num and ‘stringnum’ with specific type assignments, resulting in type-checking errors because the assignments do not match the expected types, and finally logs the variables.
Javascript
type Num<T> = T extends number[] ? number : (T extends string[] ? string : never) // Return num const num: Num<number[]> = 4; // Return invalid const stringnum: Num<number> = "7" ; console.log(num, stringnum); |
Output:
Contact Us