JavaScript and TypeScript course · Module 6: TypeScript Basics

Type aliases

13 min read ·
In this lesson10

Welcome back to the Jurassic Park genetics laboratory! Dr. Henry Wu will today introduce us to an extremely useful TypeScript mechanism - type aliases. Just as scientists in the park use shorthand names for complex genetic sequences, programmers use type aliases to simplify complex type definitions.

What are type aliases?

A type alias is simply a name we give to an existing type. We can alias both simple and complex types, which makes code more readable and easier to maintain. It's like naming different DNA mixtures so they're easier to refer to during lab work.

Basic syntax

We define type aliases using the type keyword:

// Simple type alias for string
type SpeciesID = string;

// Using the alias
const tRexID: SpeciesID = "TREX-01";
const velociraptorID: SpeciesID = "VELOC-01";

Aliases for primitive types

Type aliases can be applied to simple types, which can be helpful for documentation and code intent:

// Aliases for simple types
type SecurityLevel = number;
type SpeciesName = string;
type IsPredator = boolean;

// Function using type aliases
function setEnclosureLevel(species: SpeciesName, predator: IsPredator): SecurityLevel {
  if (predator) {
    if (species === "Tyrannosaurus") return 5;
    if (species === "Velociraptor") return 4;
    return 3; // Other predators
  } else {
    return 2; // Herbivores
  }
}

const trexLevel = setEnclosureLevel("Tyrannosaurus", true); // 5
console.log(`Security level for T-Rex: ${trexLevel}`);

Aliases for complex types

Type aliases become especially useful when defining complex types such as objects, unions or arrays:

// Alias for object type (similar to interface)
type Dinosaur = {
  id: string;
  name: string;
  species: string;
  age: number;
  weight: number;
  predator: boolean;
};

// Alias for union type - different identifiers
type DinosaurID = string | number;

// Alias for tuple - GPS coordinates with description
type Location = [number, number, string];

// Alias for array
type SpeciesList = string[];

// Alias for an object literal with optional fields
type HealthStatus = {
  overallHealth: "excellent" | "good" | "average" | "poor" | "critical";
  temperature?: number;
  heartRate?: number;
  treatmentPriority?: 1 | 2 | 3 | 4 | 5;
  notes?: string;
};

// Creating objects based on type aliases
const rexLocation: Location = [35.6895, 139.6917, "T-Rex Enclosure, northern fence"];
const parkSpecies: SpeciesList = ["Tyrannosaurus", "Velociraptor", "Triceratops", "Brachiosaurus"];

const rexStatus: HealthStatus = {
  overallHealth: "good",
  temperature: 38.2,
  treatmentPriority: 2,
  notes: "Recently slightly reduced appetite"
};

// Function working on type alias
function prepareDinosaurReport(dino: Dinosaur, status: HealthStatus, location: Location): string {
  const [lat, lng, description] = location;

  return `
    Dinosaur report:
    ID: ${dino.id}
    Name: ${dino.name}
    Species: ${dino.species}
    Age: ${dino.age} years
    Weight: ${dino.weight} kg
    Predator: ${dino.predator ? "Yes" : "No"}

    Health status: ${status.overallHealth}
    ${status.temperature ? `Temperature: ${status.temperature}°C` : ""}
    ${status.heartRate ? `Heart rate: ${status.heartRate} beats/min` : ""}

    Location: ${description} (${lat}, ${lng})
  `;
}

Aliases with generic types

Type aliases can also be generic, giving us even greater flexibility:

// Generic type alias for monitoring system data
type MonitoringData<T> = {
  measurementTime: Date;
  value: T;
  unit: string;
  valid: boolean;
};

// Using the generic type alias for different types of measurements
type TemperatureMeasurement = MonitoringData<number>;
type ActivityMeasurement = MonitoringData<"low" | "medium" | "high">;
type StressLevelMeasurement = MonitoringData<1 | 2 | 3 | 4 | 5>;

// Function analyzing monitoring data
function analyzeData<T>(data: MonitoringData<T>): void {
  console.log(`Measurement from ${data.measurementTime.toISOString()}`);
  console.log(`Value: ${data.value} ${data.unit}`);
  console.log(`Status: ${data.valid ? "Valid" : "Needs attention"}`);
}

// Sample usage
const waterTemperature: TemperatureMeasurement = {
  measurementTime: new Date(),
  value: 24.5,
  unit: "°C",
  valid: true
};

const trexActivityLevel: ActivityMeasurement = {
  measurementTime: new Date(),
  value: "high",
  unit: "activity level",
  valid: false // Needs attention because T-Rex is too active
};

analyzeData(waterTemperature);
analyzeData(trexActivityLevel);

Recursive type aliases

Type aliases can be recursive, which is useful for modeling tree structures such as dinosaur species hierarchies or park organizational structures:

// Recursive type alias for dinosaur category hierarchy
type DinosaursCategory = {
  name: string;
  description?: string;
  subcategories?: DinosaursCategory[];
};

// Creating a category hierarchy
const taxonomy: DinosaursCategory = {
  name: "Dinosaurs",
  description: "Main classification of dinosaurs in Jurassic Park",
  subcategories: [
    {
      name: "Theropods",
      description: "Carnivorous, bipedal dinosaurs",
      subcategories: [
        {
          name: "Tyrannosaurids",
          subcategories: [
            { name: "Tyrannosaurus Rex" }
          ]
        },
        {
          name: "Deinonychosaurs",
          subcategories: [
            { name: "Velociraptor" },
            { name: "Deinonychus" }
          ]
        }
      ]
    },
    {
      name: "Sauropods",
      description: "Large, four-legged herbivores with long necks",
      subcategories: [
        { name: "Brachiosaurus" },
        { name: "Diplodocus" }
      ]
    }
  ]
};

// Function to render the taxonomy tree
function displayTaxonomy(category: DinosaursCategory, level: number = 0): void {
  const indent = "  ".repeat(level);
  console.log(`${indent}${category.name}`);

  if (category.description) {
    console.log(`${indent}  Description: ${category.description}`);
  }

  if (category.subcategories && category.subcategories.length > 0) {
    category.subcategories.forEach(subcategory => {
      displayTaxonomy(subcategory, level + 1);
    });
  }
}

displayTaxonomy(taxonomy);

Type aliases vs interfaces

Type aliases are often compared to interfaces because in many cases they can be used interchangeably. However, there are some key differences between them:

// Structure definition using interface
interface DinosaurInterface {
  id: string;
  name: string;
  species: string;
}

// Equivalent definition using type alias
type DinosaurType = {
  id: string;
  name: string;
  species: string;
};

// Both work similarly for basic use
const dino1: DinosaurInterface = { id: "001", name: "Rex", species: "Tyrannosaurus" };
const dino2: DinosaurType = { id: "002", name: "Blue", species: "Velociraptor" };

Key differences between type aliases and interfaces

  1. Extensibility:

    • Interfaces can be extended by declaring them multiple times
    • Type aliases cannot be "opened" - once defined, an alias cannot be extended later
    // Interface can be extended by multiple declarations
    interface AnimalInterface {
      id: string;
      species: string;
    }
    
    // Adding new fields to the existing interface
    interface AnimalInterface {
      age: number;
      weight: number;
    }
    
    // Now AnimalInterface has all four fields
    const animal: AnimalInterface = {
      id: "001",
      species: "Tyrannosaurus",
      age: 7,
      weight: 7000
    };
    
    // A type alias cannot be extended this way
    type AnimalType = {
      id: string;
      species: string;
    }
    
    // This would cause an error: Duplicate identifier 'AnimalType'
    // type AnimalType = {
    //   age: number;
    //   weight: number;
    // }
  2. Complex types:

    • Type aliases can directly represent unions, intersections and other advanced types
    • Interfaces are more focused on defining the shape of objects
    // Only possible with type aliases
    type SecurityStatus = "normal" | "elevated" | "threat";
    type GPSCoordinates = [number, number];
    type AnimalID = string | number;
    
    // With interfaces this would be more cumbersome
  3. Interfaces for classes:

    • Interfaces are the natural choice for defining contracts that classes must implement
    • Type aliases are more flexible for defining complex types
    // Interface for a class
    interface MonitoringSystem {
      start(): void;
      stop(): void;
      getStatus(): string;
    }
    
    // Class implementing the interface
    class EnclosureMonitoring implements MonitoringSystem {
      start() { console.log("Enclosure monitoring started"); }
      stop() { console.log("Enclosure monitoring stopped"); }
      getStatus() { return "Active"; }
    }

Combining type aliases with other TypeScript features

Type aliases can be combined with other TypeScript features, creating powerful abstractions:

// Combining with union types
type DinosaurData =
  | { type: "basic"; id: string; species: string }
  | { type: "extended"; id: string; species: string; age: number; weight: number }
  | { type: "full"; id: string; species: string; age: number; weight: number; history: string[]; healthStatus: string };

// Function processing different levels of data
function processDinosaurData(data: DinosaurData): void {
  console.log(`Processing data for ID: ${data.id}, species: ${data.species}`);

  // We use the discriminated union to determine the data type
  switch (data.type) {
    case "basic":
      console.log("Processing basic data");
      break;
    case "extended":
      console.log(`Age: ${data.age}, Weight: ${data.weight} kg`);
      break;
    case "full":
      console.log(`Age: ${data.age}, Weight: ${data.weight} kg`);
      console.log(`History: ${data.history.join(", ")}`);
      console.log(`Health status: ${data.healthStatus}`);
      break;
  }
}

// Usage examples
const basic: DinosaurData = {
  type: "basic",
  id: "TRX-001",
  species: "Tyrannosaurus"
};

const extended: DinosaurData = {
  type: "extended",
  id: "VEL-001",
  species: "Velociraptor",
  age: 4,
  weight: 150
};

const full: DinosaurData = {
  type: "full",
  id: "TRI-001",
  species: "Triceratops",
  age: 10,
  weight: 8000,
  history: ["Born: 2013", "Transfer from Location B: 2016", "Broken horns: 2018", "Recovery: 2019"],
  healthStatus: "Good"
};

processDinosaurData(basic);
processDinosaurData(extended);
processDinosaurData(full);

Combining utility types with type aliases

TypeScript offers built-in utility types that can be combined with type aliases, giving us even greater data modeling capabilities:

// Base interface for a dinosaur
interface Dinosaur {
  id: string;
  name: string;
  species: string;
  age: number;
  weight: number;
  gender: "male" | "female";
  predator: boolean;
  nocturnal: boolean;
  healthStatus: "excellent" | "good" | "needs attention" | "sick" | "critical";
}

// Type aliases using utility types

// Read-only type - useful for data that should not be modified
type DinosaurReadOnly = Readonly<Dinosaur>;

// Type with selected fields - useful for partial data
type DinosaurBasic = Pick<Dinosaur, "id" | "name" | "species">;

// Type with omitted fields - useful when we want to exclude certain data
type DinosaurWithoutStatus = Omit<Dinosaur, "healthStatus">;

// Type with optional fields - useful for partial updates
type DinosaurPartial = Partial<Dinosaur>;

// Type with required fields - forcing all fields to be defined
type DinosaurRequired = Required<Dinosaur>;

// Record type - useful for key-indexed collections
type DinosaursDatabase = Record<string, Dinosaur>;

// Usage examples
const rexReadOnly: DinosaurReadOnly = {
  id: "TRX-001",
  name: "Rex",
  species: "Tyrannosaurus",
  age: 7,
  weight: 7000,
  gender: "female",
  predator: true,
  nocturnal: false,
  healthStatus: "good"
};

// rexReadOnly.age = 8; // Error: Cannot assign to 'age' because it is a read-only property

const rexBasic: DinosaurBasic = {
  id: "TRX-001",
  name: "Rex",
  species: "Tyrannosaurus"
};

// Partial data update
function updateDinosaurData(id: string, data: DinosaurPartial): void {
  console.log(`Updating data for dinosaur ${id}`);
  console.log(data);
  // In a real application we would update the data in the database
}

updateDinosaurData("TRX-001", {
  age: 8,
  weight: 7200,
  healthStatus: "needs attention"
});

// Dinosaur database
const database: DinosaursDatabase = {
  "TRX-001": {
    id: "TRX-001",
    name: "Rex",
    species: "Tyrannosaurus",
    age: 7,
    weight: 7000,
    gender: "female",
    predator: true,
    nocturnal: false,
    healthStatus: "good"
  },
  "VEL-001": {
    id: "VEL-001",
    name: "Blue",
    species: "Velociraptor",
    age: 4,
    weight: 150,
    gender: "female",
    predator: true,
    nocturnal: true,
    healthStatus: "excellent"
  }
};

console.log(`Number of dinosaurs in the database: ${Object.keys(database).length}`);

Practical example of the Jurassic Park data model

Let's now see how we can use type aliases together with other TypeScript features to create a comprehensive data model for the Jurassic Park management system:

// Base types
type ID = string;
type Coordinates = [number, number];
type AccessLevel = 1 | 2 | 3 | 4 | 5;
type ActivityStatus = "active" | "inactive" | "under maintenance";
type HealthStatus = "excellent" | "good" | "needs attention" | "sick" | "critical";

// Dinosaur types
type TaxonomicGroup = "theropods" | "sauropods" | "ceratopsians" | "stegosaurs" | "ankylosaurs";

type DietClass = "herbivore" | "carnivore" | "omnivore";

type SpeciesData = {
  name: string;
  taxonomicGroup: TaxonomicGroup;
  diet: DietClass;
  geologicalEra: string;
  averageWeight: number;
  averageLength: number;
  averageAge: number;
  threat: AccessLevel;
  description: string;
};

type Specimen = {
  id: ID;
  species: string;
  firstName: string;
  age: number;
  weight: number;
  gender: "male" | "female";
  status: HealthStatus;
  location: ID;
  arrivalDate: Date;
  history: MedicalHistory[];
};

type MedicalHistory = {
  date: Date;
  type: "examination" | "treatment" | "vaccination" | "surgery";
  description: string;
  veterinarian: ID;
};

// Employee types
type Position =
  | "director"
  | "researcher"
  | "veterinarian"
  | "trainer"
  | "security"
  | "maintenance"
  | "technician"
  | "guide";

type Employee = {
  id: ID;
  firstName: string;
  lastName: string;
  position: Position;
  accessLevel: AccessLevel;
  hireDate: Date;
  contact: {
    phone: string;
    email: string;
    address?: string;
  };
  specializationAreas?: string[];
};

// Location types
type LocationType =
  | "enclosure"
  | "laboratory"
  | "operations center"
  | "public zone"
  | "dining"
  | "shop"
  | "attraction";

type SecuritySystems = {
  fence: boolean;
  videoMonitoring: boolean;
  motionSensors: boolean;
  backupPower: boolean;
  electricVoltage?: number; // only for predator enclosures
};

type Location = {
  id: ID;
  name: string;
  type: LocationType;
  coordinates: Coordinates;
  area: number; // in hectares
  capacity: number; // maximum number of people/specimens
  requiredAccessLevel: AccessLevel;
  status: ActivityStatus;
  securitySystems: SecuritySystems;
};

// Event types
type EventType =
  | "dinosaurEscape"
  | "systemFailure"
  | "accident"
  | "illness"
  | "birth"
  | "death"
  | "specimenTransfer"
  | "weatherThreat";

type Event = {
  id: ID;
  type: EventType;
  date: Date;
  location: ID;
  dinosaurParticipants?: ID[];
  employeeParticipants?: ID[];
  description: string;
  status: "in progress" | "resolved" | "closed";
  priority: 1 | 2 | 3 | 4 | 5;
  preventiveActions?: string[];
};

// Park management system
type ManagementSystem = {
  dinosaurs: Record<ID, Specimen>;
  species: Record<string, SpeciesData>;
  employees: Record<ID, Employee>;
  locations: Record<ID, Location>;
  events: Record<ID, Event>;

  // System methods
  addSpecimen: (specimen: Omit<Specimen, "id">) => ID;
  updateSpecimenStatus: (id: ID, status: HealthStatus) => void;
  moveSpecimen: (id: ID, newLocation: ID) => boolean;
  findSpecimens: (filters: Partial<Specimen>) => Specimen[];
  generateStatusReport: () => StatusReport;
};

type StatusReport = {
  specimenCount: number;
  speciesDistribution: Record<string, number>;
  healthStatuses: Record<HealthStatus, number>;
  locationOccupancy: Record<ID, { capacity: number; current: number }>;
  recentEvents: Event[];
  alerts: string[];
};

// Simulating part of the system
const jurassicParkSystem: Partial<ManagementSystem> = {
  dinosaurs: {},
  species: {
    "Tyrannosaurus": {
      name: "Tyrannosaurus Rex",
      taxonomicGroup: "theropods",
      diet: "carnivore",
      geologicalEra: "late Cretaceous",
      averageWeight: 7000,
      averageLength: 12,
      averageAge: 30,
      threat: 5,
      description: "One of the largest predators that ever walked the Earth."
    },
    "Velociraptor": {
      name: "Velociraptor",
      taxonomicGroup: "theropods",
      diet: "carnivore",
      geologicalEra: "late Cretaceous",
      averageWeight: 15,
      averageLength: 1.8,
      averageAge: 25,
      threat: 4,
      description: "Small, fast and intelligent predator, hunting in packs."
    }
  },
  locations: {
    "LOC-001": {
      id: "LOC-001",
      name: "T-Rex Paddock",
      type: "enclosure",
      coordinates: [20.1234, -75.8765],
      area: 8,
      capacity: 2,
      requiredAccessLevel: 4,
      status: "active",
      securitySystems: {
        fence: true,
        videoMonitoring: true,
        motionSensors: true,
        backupPower: true,
        electricVoltage: 10000
      }
    }
  }
};

// Function demonstrating usage of the types
function demonstrateManagementSystem() {
  console.log("Jurassic Park Management System");
  console.log("----------------------------------");

  console.log("Available species:");
  Object.values(jurassicParkSystem.species || {}).forEach(species => {
    console.log(`- ${species.name} (${species.diet}, threat: ${species.threat})`);
  });

  console.log("\nAvailable locations:");
  Object.values(jurassicParkSystem.locations || {}).forEach(loc => {
    console.log(`- ${loc.name} (type: ${loc.type}, status: ${loc.status}, access: level ${loc.requiredAccessLevel})`);
  });
}

demonstrateManagementSystem();

Summary

Type aliases in TypeScript are a powerful mechanism that allows the creation of more readable, maintainable and safe code. In the context of managing a complex system like Jurassic Park, type aliases allow us to accurately model data and the relationships between them.

Type alias featureUse in Jurassic Park
Basic aliasesTypes of identifiers, security levels
Complex type aliasesData structures for dinosaurs, employees, locations
Generic aliasesMonitoring system for different parameters
Recursive typesSpecies hierarchies, organizational structure
Discriminated unionsDifferent data levels, types of events
Utility typesManaging data mutability and accessibility

Dr. Wu summarizes: "Type aliases are like our checklists and protocols in the laboratory - they allow us to clearly define what data and operations should look like, while making the whole system more understandable. In a project as complex as Jurassic Park, where the smallest error can lead to catastrophic consequences, such precise tools are invaluable."

Code for this lesson: index.ts
// Type Aliases in Jurassic Park
console.log("Type Aliases TypeScript\n");

// ===========================================
// 1. Basic type aliases
// ===========================================
console.log("=== BASIC TYPE ALIASES ===");

// Alias for simple types
type DinosaurID = string | number;
type Weight = number;
type Species = string;

let id1: DinosaurID = "DINO-001";
let id2: DinosaurID = 123;
let weight: Weight = 8000;
let species: Species = "Tyrannosaurus Rex";

console.log("ID:", id1, id2);
console.log("Weight:", weight);
console.log("Species:", species);

// ===========================================
// 2. Type vs Interface
// ===========================================
console.log("\n=== TYPE VS INTERFACE ===");

// Type alias
type DinosaurType = {
  name: string;
  species: string;
  age: number;
};

// Interface
interface DinosaurInterface {
  name: string;
  species: string;
  age: number;
}

const dino1: DinosaurType = {
  name: "Rex",
  species: "T-Rex",
  age: 5
};

const dino2: DinosaurInterface = {
  name: "Blue",
  species: "Velociraptor",
  age: 3
};

console.log("Type:", dino1);
console.log("Interface:", dino2);

// ===========================================
// 3. Union types with aliases
// ===========================================
console.log("\n=== UNION TYPES ===");

type Diet = "carnivore" | "herbivore" | "omnivore";
type Period = "Triassic" | "Jurassic" | "Cretaceous";
type SecurityLevel = "low" | "medium" | "high" | "critical";

type Dinosaur = {
  name: string;
  diet: Diet;
  period: Period;
  dangerLevel: SecurityLevel;
};

const trex: Dinosaur = {
  name: "Tyrannosaurus Rex",
  diet: "carnivore",
  period: "Cretaceous",
  dangerLevel: "critical"
};

console.log("T-Rex:", trex);

// ===========================================
// 4. Intersection types with aliases
// ===========================================
console.log("\n=== INTERSECTION TYPES ===");

type HasName = {
  name: string;
};

type HasWeight = {
  weight: number;
};

type HasDiet = {
  diet: Diet;
};

// Combining types
type CompleteDinosaur = HasName & HasWeight & HasDiet & {
  species: string;
};

const velociraptor: CompleteDinosaur = {
  name: "Blue",
  weight: 350,
  diet: "carnivore",
  species: "Velociraptor"
};

console.log("Complete dinosaur:", velociraptor);

// ===========================================
// 5. Function types
// ===========================================
console.log("\n=== FUNCTION TYPES ===");

// Function type
type DinosaurFilter = (dino: Dinosaur) => boolean;
type DinosaurTransformer = (dino: Dinosaur) => string;
type DinosaurComparator = (a: Dinosaur, b: Dinosaur) => number;

const carnivoreFilter: DinosaurFilter = (dino) => dino.diet === "carnivore";
const nameTransformer: DinosaurTransformer = (dino) => `${dino.name}`;
const dangerComparator: DinosaurComparator = (a, b) => {
  const levels = { low: 1, medium: 2, high: 3, critical: 4 };
  return levels[b.dangerLevel] - levels[a.dangerLevel];
};

console.log("Is carnivore:", carnivoreFilter(trex));
console.log("Transformed:", nameTransformer(trex));

// ===========================================
// 6. Tuple types
// ===========================================
console.log("\n=== TUPLE TYPES ===");

type Coordinates = [latitude: number, longitude: number];
type DinosaurData = [name: string, weight: number, isCarnivore: boolean];
type RGB = [red: number, green: number, blue: number];

const paddockLocation: Coordinates = [22.3964, -159.5261];
const dinoInfo: DinosaurData = ["Rexy", 8000, true];
const warningColor: RGB = [255, 0, 0];

console.log("Location:", paddockLocation);
console.log("Dino info:", dinoInfo);
console.log("Warning color:", warningColor);

// ===========================================
// 7. Mapped types with aliases
// ===========================================
console.log("\n=== MAPPED TYPES ===");

type DinosaurStats = {
  health: number;
  hunger: number;
  energy: number;
  happiness: number;
};

// All fields as readonly
type ReadonlyStats = {
  readonly [K in keyof DinosaurStats]: DinosaurStats[K];
};

// All fields as optional
type PartialStats = {
  [K in keyof DinosaurStats]?: DinosaurStats[K];
};

const stats: DinosaurStats = {
  health: 100,
  hunger: 50,
  energy: 80,
  happiness: 90
};

const readonlyStats: ReadonlyStats = stats;
// readonlyStats.health = 90; // Error

const partialStats: PartialStats = {
  health: 100,
  energy: 80
  // remaining fields optional
};

console.log("Stats:", stats);
console.log("Partial stats:", partialStats);

// ===========================================
// 8. Conditional types
// ===========================================
console.log("\n=== CONDITIONAL TYPES ===");

// Conditional type
type IsCarnivore<T> = T extends { diet: "carnivore" } ? true : false;

type TRexIsCarnivore = IsCarnivore<typeof trex>; // true
type VelociraptorIsCarnivore = IsCarnivore<typeof velociraptor>; // true

// Extract - extracts types satisfying condition
type DinosaurSize = "small" | "medium" | "large" | "extra-large";
type LargeSizes = Extract<DinosaurSize, "large" | "extra-large">;

// Exclude - removes types satisfying condition
type SmallMediumSizes = Exclude<DinosaurSize, "large" | "extra-large">;

console.log("Conditional types defined");

// ===========================================
// 9. Utility types with aliases
// ===========================================
console.log("\n=== UTILITY TYPES ===");

type BaseDinosaur = {
  id: string;
  name: string;
  species: string;
  weight: number;
};

// Partial - all fields optional
type PartialDinosaur = Partial<BaseDinosaur>;

// Required - all fields required
type RequiredDinosaur = Required<BaseDinosaur>;

// Pick - select specific fields
type DinosaurSummary = Pick<BaseDinosaur, "name" | "species">;

// Omit - remove specific fields
type PublicDinosaur = Omit<BaseDinosaur, "id">;

// Record - mapping keys to a type
type DinosaurCollection = Record<string, BaseDinosaur>;

const partialDino: PartialDinosaur = {
  name: "Rex"
  // all other fields optional
};

const summary: DinosaurSummary = {
  name: "Rexy",
  species: "T-Rex"
};

const collection: DinosaurCollection = {
  "t-rex": {
    id: "001",
    name: "Rexy",
    species: "T-Rex",
    weight: 8000
  },
  "velociraptor": {
    id: "002",
    name: "Blue",
    species: "Velociraptor",
    weight: 350
  }
};

console.log("Partial:", partialDino);
console.log("Summary:", summary);
console.log("Collection:", collection);

// ===========================================
// 10. Summary
// ===========================================
console.log("\n=== SUMMARY ===");
console.log("Type Aliases - names for types");
console.log("Union & Intersection - combining types");
console.log("Function Types - types of functions");
console.log("Tuple Types - tuples");
console.log("Mapped Types - type transformation");
console.log("Conditional Types - types that depend on a condition");
console.log("Utility Types - built-in tools");

console.log("\nType Aliases mastered!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is a type alias in TypeScript?

  2. 2. What is a type guard in TypeScript?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create a type alias DinoStatus and a function with a type guard that checks whether a dinosaur is carnivorous.

  • Click in order

    Arrange the elements of a type assertion in TypeScript:

  • Vertical ordering

    Order type checking methods in TypeScript from simplest to most advanced:

  1. QuestionType Alias in TypeScript
  2. QuestionType Guards
  3. Coding taskPractice: Type Aliases and Type Guards
  4. Click in orderSorting: Type Assertion
  5. QuestionThe as Operator in TypeScript
  6. Put in orderType Checking Methods

Useful articles