Typescript Foundations / Objects & Interfaces

Type aliases

πŸ‘‰ A type alias lets you define a custom name for a type (including object types, unions, functions, etc.).

πŸ‘‰ It makes your code cleaner, more readable, and DRY (Don't Repeat Yourself).


βœ… Basic Syntax

type AliasName = Type;

✍ Example 1: Primitive Type Alias

type Username = string;

let user1: Username = "Alice";
let user2: Username = "Tisha";

✍ Example 2: Union Type Alias

type Status = "pending" | "approved" | "rejected";

let orderStatus: Status = "approved";
// orderStatus = "done"; // ❌ Error

✍ Example 3: Array or Tuple Alias

type StringArray = string[];
type Point = [number, number];

const names: StringArray = ["Alice", "Bob"];
const coord: Point = [10, 20];

✍ Example 4: Function Type Alias

type Logger = (message: string, level?: "info" | "error") => void;

const log: Logger = (msg, level = "info") => {
  console.log(`[${level.toUpperCase()}]: ${msg}`);
};

✍ Example 5: Object Type Alias

type User = {
  name: string;
  age: number;
  isAdmin?: boolean;
};

const user: User = {
  name: "Codeveda",
  age: 21
};

πŸ”„ Combined Example


βœ… Summary

Feature

Example

Basic Alias

type ID = number

Object Alias

type User = { name: string; age: number }

Union Types

`type Status = "open"

Function Alias

type Fn = (x: string) => void

Reusable Types

type Point = [number, number]

Combined Types

type AdminUser = Admin & Person


πŸ’‘ Type Alias vs Interface

Feature

type

interface

Aliases for any type (primitives, unions, functions, etc.)

βœ…

❌

Extends/Implements for OOP

βœ… via &

βœ… with extends

Declaration merging

❌

βœ…

πŸ”Ή Use type for flexibility and unions

πŸ”Ή Use interface for class-like or extendable structures