Open In App

TypeScript Aliases Type

Last Updated : 22 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In TypeScript, a type alias allows you to assign a custom name to an existing type, enhancing code readability and reusability.

  • Provide a shorthand for complex types like unions or objects.
  • Allow naming of primitive types, object types, or functions for clarity.
  • Simplify repetitive type definitions and improve maintainability.
type Point = {
    x: number;
    y: number;
};

type Shape = "circle" | "square" | "rectangle";

function drawShape(shape: Shape, position: Point): void {
    console.log(`Drawing a ${shape} at (${position.x}, ${position.y})`);
}

drawShape("circle", { x: 10, y: 20 });
  • Point is a type alias for an object with x and y as number.
  • Shape is a type alias for a union of specific string literals.
  • The drawShape function accepts a Shape and a Point, ensuring strong type safety and clarity.

Output:

Drawing a circle at (10, 20)

Parameters of Type Aliases

  • AliasName:
    • This is the name you assign to the type alias. It must be a valid TypeScript identifier.
    • Example: Point, Shape, UserProfile.
  • ExistingType:
    • This refers to the actual data type or structure the alias represents.
    • Example: string, number, { x: number; y: number; }.

More Examples of TypeScript aliases Type

Alias for a Union Type

type ID = number | string;

let userId: ID;
userId = 101;       // Valid assignment
userId = "A123";    // Also valid
  • ID is a type alias that allows a variable to be either a number or a string.
  • This provides flexibility for userId to accept both numeric and alphanumeric identifiers.

Output:

Origin: { x: 0, y: 0 }
Distance from Origin: 0

Defining a User Profile with Type Aliases

type UserProfile = {
    username: string;
    email: string;
    age: number;
};

const user: UserProfile = {
    username: "Akshit Saxena",
    email: "akshit.saxena@geeksforgeeks.com",
    age: 24,
};

function greetUser(profile: UserProfile): string {
    return `Hello, ${profile.username}! 
    You are ${profile.age} years old. 
    Your email is ${profile.email}.`;
}

console.log(greetUser(user));
  • UserProfile is a type alias for an object with username, email, and age properties.
  • The greetUser function utilizes this alias to ensure it receives a properly structured user profile.

Output:

Hello, Akshit Saxena! 
You are 24 years old.
Your email is akshit.saxena@geeksforgeeks.com.

Using Type Aliases for Union Types

type ID = number | string;

function displayId(id: ID): void {
    console.log(`The ID is ${id}`);
}

displayId(101);
displayId("A102");
  • ID is a type alias representing a union of number and string.
  • The displayId function accepts an ID, allowing for flexible input types.

Output:

The ID is 101
The ID is A102

Best Practices for Using TypeScript Type Aliases

  • Use Descriptive Names: Choose clear and meaningful names for type aliases to enhance code readability.
  • Keep Types Focused: Define type aliases for specific, well-defined structures to maintain clarity.
  • Document Complex Types: Provide comments or documentation for complex type aliases to aid understanding.

TypeScript Aliases Type - FAQs

What are type aliases in TypeScript?

Type aliases allow you to create a new name for an existing type, simplifying complex type definitions and improving code readability.

When should I use a type alias instead of an interface?

Use type aliases for unions, intersections, or when defining primitive types; use interfaces for defining object shapes that may require extension.

Can type aliases be recursive?

Yes, type aliases can reference themselves to define recursive types, enabling the representation of structures like linked lists or trees.

Do type aliases affect runtime performance?

No, type aliases are a compile-time feature and do not impact the runtime performance of your code.

Can I use generics with type aliases?

Yes, type aliases can be combined with generics to create flexible and reusable type definitions.


Next Article

Similar Reads

three90RightbarBannerImg