TypeScript Aliases Type (original) (raw)

Last Updated : 22 Jan, 2025

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

type Point = { x: number; y: number; };

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

function drawShape(shape: Shape, position: Point): void { console.log(Drawing a <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>s</mi><mi>h</mi><mi>a</mi><mi>p</mi><mi>e</mi></mrow><mi>a</mi><mi>t</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">{shape} at (</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">s</span><span class="mord mathnormal">ha</span><span class="mord mathnormal">p</span><span class="mord mathnormal">e</span></span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mopen">(</span></span></span></span>{position.x}, ${position.y})); }

drawShape("circle", { x: 10, y: 20 });

``

**Output:

Drawing a circle at (10, 20)

**Parameters of Type Aliases

**More Examples of TypeScript aliases Type

**Alias for a Union Type

JavaScript `

type ID = number | string;

let userId: ID; userId = 101; // Valid assignment userId = "A123"; // Also valid

`

**Output:

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

**Defining a User Profile with Type Aliases

JavaScript ``

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));

``

**Output:

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

Using Type Aliases for Union Types

JavaScript ``

type ID = number | string;

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

displayId(101); displayId("A102");

``

**Output:

The ID is 101
The ID is A102

Best Practices for Using TypeScript Type Aliases