Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A generic type alias is a parameterized type definition that accepts one or more type variables, enabling the creation of dynamic, reusable type blueprints. By appending type parameters enclosed in angle brackets (<T>) to a type declaration, the alias acts as a type-level function, substituting the provided type arguments into the alias’s definition upon instantiation.
type AliasName<TypeParameter1, TypeParameter2> = /* Definition using parameters */;
Unlike generic interfaces, which are restricted to defining object shapes, generic type aliases can resolve to any valid TypeScript type, including primitives, unions, intersections, tuples, and function signatures.
// Resolving to a union type
type Nullable<T> = T | null | undefined;

// Resolving to a tuple type
type Pair<T, U> = [T, U];

Type Constraints

Type parameters within an alias can be restricted using the extends keyword. This enforces a structural contract, ensuring that any type argument passed to the generic alias contains specific properties or matches a specific type signature.
type Entity<T extends { id: string }> = T & { createdAt: Date };

// Valid: matches the constraint
type UserEntity = Entity<{ id: string; name: string }>; 

// Invalid: Type '{ name: string; }' does not satisfy the constraint '{ id: string; }'.
type InvalidEntity = Entity<{ name: string }>; 

Default Type Arguments

Generic type aliases support default type parameters via the = operator. If a type argument is omitted during instantiation, the compiler falls back to the specified default type. Default parameters must appear after all required type parameters in the declaration.
type ApiResponse<T, E = Error> = {
    success: boolean;
    data?: T;
    error?: E;
};

// Instantiation with both arguments
type CustomResponse = ApiResponse<string, TypeError>;

// Instantiation relying on the default argument (E resolves to Error)
type StandardResponse = ApiResponse<string>;

Composition with Advanced Types

Generic type aliases are the foundational syntax for constructing TypeScript’s advanced type mechanics, specifically conditional types and mapped types, as both require a type parameter to evaluate or iterate over. Conditional Types: A generic alias can use the ternary operator syntax to evaluate type relationships dynamically.
type IsArray<T> = T extends any[] ? true : false;
Mapped Types: A generic alias can iterate over the keys of a provided type parameter to transform its properties.
type OptionalReadonly<T> = {
    readonly [K in keyof T]?: T[K];
};
Master TypeScript with Deep Grasping Methodology!Learn More