Or type

2 snippets in TypeScript

Also written as and type

TSTypeScript

Union Types

TS · Type Aliases
syntax
type Name = TypeA | TypeB | TypeC;
example
type Status = "pending" | "active" | "archived";
type ApiResponse = SuccessResult | ErrorResult;

interface SuccessResult {
  ok: true;
  data: unknown;
}
interface ErrorResult {
  ok: false;
  errorCode: number;
  message: string;
}

function handleResponse(res: ApiResponse) {
  if (res.ok) {
    console.log(res.data); // narrowed to SuccessResult
  } else {
    console.error(res.message); // narrowed to ErrorResult
  }
}
output
// Union means 'one of these types' — must narrow before accessing specific members

Note You can only access properties common to ALL members of a union without narrowing first. Use a shared discriminant property (like 'ok' above) to let TypeScript narrow automatically in conditionals.

Intersection Types

TS · Type Aliases
syntax
type Name = TypeA & TypeB;
example
type WithId = { id: string };
type WithTimestamps = { createdAt: Date; updatedAt: Date };

type UserRecord = WithId & WithTimestamps & {
  email: string;
  displayName: string;
};

const user: UserRecord = {
  id: "usr_001",
  email: "[email protected]",
  displayName: "Dev User",
  createdAt: new Date(),
  updatedAt: new Date(),
};
output
// Intersection combines all properties from all types

Note Intersection means 'all of these combined'. If two types have the same property with incompatible types, the intersected property becomes never (which usually means a mistake). Intersections are great for mixin-style composition.