Open In App

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

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.




// 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.




// 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@geeksforgeeks.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@geeksforgeeks.com.

Reference: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases


Article Tags :