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

Conditional Types

Conditional types allow you to define types based on conditions.


type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
      

Mapped Types

Mapped types allow you to create new types by transforming existing ones.


type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

type Person = { name: string; age: number };
type ReadonlyPerson = Readonly<Person>;
      

Template Literal Types

Template literal types allow you to create complex string types.


type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"
      

Utility Types

TypeScript provides several utility types to simplify common type transformations.


interface User {
  id: number;
  name: string;
  email: string;
}

type PartialUser = Partial<User>;
type ReadonlyUser = Readonly<User>;
type PickUser = Pick<User, "id" | "name">;
      

Best Practices

Next: Classes and Interfaces in TypeScript