CodeToLive

Advanced Types in TypeScript

TypeScript provides advanced type features that allow you to create more flexible and reusable code.

Union Types

Union types allow a variable to hold values of multiple types.


let value: string | number;
value = "Hello";
value = 42;
      

Intersection Types

Intersection types combine multiple types into one.


type Person = { name: string };
type Employee = { id: number };
type EmployeeDetails = Person & Employee;

let employee: EmployeeDetails = { name: "John", id: 123 };
      

Type Aliases

Type aliases allow you to create custom types.


type StringOrNumber = string | number;
let value: StringOrNumber;
value = "Hello";
value = 42;
      

Literal Types

Literal types allow you to specify exact values a variable can hold.


let direction: "left" | "right" | "up" | "down";
direction = "left";
      
Next: Classes and Interfaces in TypeScript