TypeScript Aliases Type
In Typescript, Type Aliases give a type a new name. They are similar to interfaces in that they can be used to name primitives and any other kinds that you’d have to define by hand otherwise. Aliasing doesn’t truly create a new type; instead, it gives that type a new name
Syntax
type AliasName = ExistingType;
Where the AliasName is the custom name you want to give to the type alias, & the ExistingType is the existing data type or structure that you want to alias.
Parameters
- AliasName: This is the identifier you choose for your type alias. It can be any valid TypeScript identifier (e.g., MyType, Point, Pair, etc.).
- ExistingType: This is the existing data type or structure you want to create an alias for. It can be any valid TypeScript type, including primitive types (e.g., number, string, boolean), object types (e.g., { x: number; y: number; }), union types, or even other type aliases.
Example 1: In this example, we define a Point type alias for objects with x and y properties, create an origin point (0, 0), and calculate its Euclidean distance using the calculateDistance function.
Javascript
// Define a type alias for a point // with x and y coordinates type Point = { x: number; y: number; }; // Create a variable of the Point type const org: Point = { x: 0, y: 0 }; // Function that calculates the distance from the origin function calculateDistance(point: Point): number { return Math.sqrt(point.x ** 2 + point.y ** 2); } // Calculate the distance from the origin const distanceFromOrigin = calculateDistance(org); console.log( "Origin:" , org); console.log( "Distance from Origin:" , distanceFromOrigin); |
Output:
Origin: { x: 0, y: 0 } Distance from Origin: 0
Example 2: In this example uses a UserProfile type alias for user profiles with username, email, and age properties. It creates a user profile object and a greetUser function that generates a greeting message based on the profile. Finally, it calls the function to store the greeting message in greetingMessage.
Javascript
// Define a type alias for a user profile type UserProfile = { username: string; email: string; age: number; }; // Create a user profile const user: UserProfile = { username: "Akshit Saxena" , email: "akshit.saxena@w3wiki.com" , age: 24, }; // Function that greets the user function greetUser(profile: UserProfile): string { return `Hello, ${profile.username}! You are ${profile.age} years old. Your email is ${profile.email}.`; } // Greet the user const greetingMessage = greetUser(user); console.log(greetingMessage); |
Output:
Hello, Akshit Saxena! You are 24 years old. Your email is akshit.saxena@w3wiki.com.
Reference: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases