Type aliases create a new name for an existing type, making your TypeScript code more readable, maintainable, and reusable. They don't create new types but instead provide a way to refer to types with more descriptive names and encapsulate complex type definitions.
One of the most common and powerful uses of type aliases is for creating union types, which allow a value to be one of several types:
Union Types
typeID=string|number;functionprintID(id:ID) {console.log(`ID: ${id}`);// Type narrowingif (typeof id ==="string") {console.log(id.toUpperCase()); } else {console.log(id.toFixed(0)); }}printID(101); // ValidprintID("202"); // Also valid// printID(true); // Error: Type 'boolean' is not assignable to type 'ID'
Type aliases can be used with literal types to create a type that can only be one of specific values:
Literal Types
typeDirection="North"|"East"|"South"|"West";functionmove(direction:Direction, steps:number) {console.log(`Moving ${steps} steps to the ${direction}`);}move("North",3); // Valid// move("Up", 3); // Error: Argument of type '"Up"' is not assignable to parameter of type 'Direction'
typeMathOperation= (a:number, b:number) =>number;constadd:MathOperation= (a, b) => a + b;constsubtract:MathOperation= (a, b) => a - b;constmultiply:MathOperation= (a, b) => a * b;constdivide:MathOperation= (a, b) => a / b;functionperformOperation(a:number, b:number, operation:MathOperation):number {returnoperation(a, b);}console.log(performOperation(10,5, add)); // 15console.log(performOperation(10,5, subtract)); // 5
// Too vaguetypeData= { ... };// More specific and clearertypeUserData= { ... };
3. Use type aliases for complex or reused types:
// Define once, use many timestypeCoordinates= { x:number; y:number;};functioncalculateDistance(point1:Coordinates, point2:Coordinates):number { ... }functionmovePoint(point:Coordinates, direction:string, distance:number):Coordinates { ... }
4. Use interfaces for object types that might be extended or implemented:
// Better as an interface if it might be extendedinterfaceApiClient {get(url:string):Promise<unknown>;post(url:string, data:unknown):Promise<unknown>;}// Better as a type aliastypeHttpMethod="GET"|"POST"|"PUT"|"DELETE";
5. Document your types with JSDoc:
/** * Represents a response from the API */typeApiResponse= {/** The returned data */ data:unknown;/** HTTP status code */ status:number;/** Success or error message */ message:string;};