// typeof
function printId(id: string | number) {
  if (typeof id === "string") {
    console.log("Uppercase:", id.toUpperCase());
  } else {
    console.log("Squared:", id * id);
  }
}

// instanceof
function formatDate(value: string | Date) {
  if (value instanceof Date) {
    return value.toLocaleDateString();
  }
  return new Date(value).toLocaleDateString();
}

// type predicate
interface Admin {
  role: "admin";
  permissions: string[];
}
interface User {
  role: "user";
  email: string;
}

function isAdmin(person: Admin | User): person is Admin {
  return person.role === "admin";
}

function printInfo(person: Admin | User) {
  if (isAdmin(person)) {
    console.log("Admin permissions:", person.permissions.join(", "));
  } else {
    console.log("User email:", person.email);
  }
}

// discriminated union
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.size * shape.size;
    default:
      const _exhaustive: never = shape;
      return _exhaustive;
  }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: