Skip to main content

Advanced types

January 30, 2024Less than 1 minute

Advanced types

Union Type

  • To allow a property to have multiple types
  • Use the | symbol to separate types
function formatCommandline(command: string[] | string) {
    let line = '';
    if (typeof command === 'string') {
        line = command.trim();
    } else {
        line = command.join(' ').trim();
    }
}

Tips

  • Union Types are most commonly used to safely represent potential error cases

Intersection Type

  • An intersection type combines multiple types into one
export interface ProgrammerEmployee {
  firstName: string;
  lastName: string;
  favoriteLanguage: string;
}

export interface BillableResource {
  hourlyRate: number;
}

let billableProgrammer: ProgrammerEmployee & BillableResource = {
  firstName: "John",
  lastName: "Doe",
  favoriteLanguage: "TypeScript",
  hourlyRate: 100,
};

console.log(billableProgrammer);