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.

Frequently asked questions

How does TypeScript handle or type?
TypeScript covers this with 2 copy-ready snippets on this page. The "Union Types" snippet in TypeScript uses `type Name = TypeA | TypeB | TypeC;`.
Which code does the TypeScript example use?
The "Union Types" snippet uses `type Name = TypeA | TypeB | TypeC;`, from the Type Aliases section of the TypeScript cheat sheet.
What other TypeScript snippets are shown for "or type"?
Besides "Union Types", this page also shows "Intersection Types".
Is there anything to watch out for?
Yes. For "Union Types": 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.