Module lessons (1/2)
Conditional Types and infer
Conditional types allow you to express non-trivial type decisions based on inheritance relationships. The syntax resembles JavaScript's ternary operator:
T extends U ? X : YIf type T is assignable to U, then the resulting type will be X, otherwise it will be Y.
Basic Conditional Types
A conditional type evaluates a condition at compile time:
type IsNumber<T> = T extends number ? true : false;
type A = IsNumber<number>; // true
type B = IsNumber<string>; // falseThis pattern is extremely powerful when combined with generics to create flexible and dynamic utility types.
Type Extraction with infer
Inside the extends clause of a conditional type, we can use the infer keyword to declare a type variable to be inferred by the compiler.
For example, if we want to extract the return type of a function:
type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type ExampleFunction = () => string;
type Return = GetReturnType<ExampleFunction>; // stringIn this example, infer R tells TypeScript to automatically determine the function's return type and make it available as R in the positive branch of the conditional.
Try it yourself
Exercise 1: The IsString Type
Create a generic type named IsString<T> that returns the literal type true if T extends string, otherwise false.
Show hint
Use the syntax type IsString<T> = T extends string ? true : false; to check the type.
Solution available after 3 attempts
Exercise 2: Extracting a type from an Array with infer
Define a generic type UnpackArray<T> that uses infer to extract the element type of an array T. If T is an array (for example U[]), return U, otherwise return the same type T.
Show hint
Use T extends (infer U)[] ? U : T to declare and return the inferred type variable U.
Solution available after 3 attempts