0
0
Typescriptprogramming~5 mins

Creating type aliases in Typescript

Choose your learning style9 modes available
Introduction

Type aliases let you give a new name to a type. This makes your code easier to read and reuse.

When you want to name a complex type to use it many times.
When you want to make your code clearer by giving meaningful names to types.
When you want to combine multiple types into one easy name.
When you want to simplify union or intersection types.
When you want to create a custom type for function parameters or return values.
Syntax
Typescript
type NewName = ExistingType;

The keyword type starts the alias.

You can use any valid type after the equals sign, like primitives, objects, unions, or intersections.

Examples
This creates a new type alias called Name that is the same as string.
Typescript
type Name = string;
This alias ID can be a number or a string.
Typescript
type ID = number | string;
This alias Point describes an object with x and y as numbers.
Typescript
type Point = { x: number; y: number };
This alias Callback is a function type that takes a string and returns nothing.
Typescript
type Callback = (data: string) => void;
Sample Program

This program creates type aliases for UserID and User. It uses them to type function parameters and variables. It then prints greetings for two users.

Typescript
type UserID = number | string;

type User = {
  id: UserID;
  name: string;
};

function greet(user: User): string {
  return `Hello, ${user.name}! Your ID is ${user.id}.`;
}

const user1: User = { id: 123, name: "Alice" };
const user2: User = { id: "abc-456", name: "Bob" };

console.log(greet(user1));
console.log(greet(user2));
OutputSuccess
Important Notes

Type aliases do not create new types, just new names for existing types.

You cannot use type aliases to create values, only types.

Use type aliases to make your code easier to understand and maintain.

Summary

Type aliases give a new name to a type for easier reuse.

They can represent simple or complex types like unions and objects.

Use them to make your code clearer and less repetitive.