Interfaces Extend While Type Unions Compose

Interfaces extend object shapes and merge across declarations; type aliases compose unions and intersections, and each side covers jobs the other cannot.

TypescriptData Integrity

Code

typescriptsnippet
24 lines
// interface:对象形状契约,支持 extends 继承扩展
interface Account {
  id: string;
}
interface AccountWithMail extends Account {
  email: string;
}

// type:union、原始值别名与交叉组合(compose)只有 type 能表达
type Role = "admin" | "viewer";
type Audit = Account & { lastSeen: number };

const user: AccountWithMail = { id: "u1", email: "[email protected]" };
const auditor: Audit = { id: "u2", lastSeen: 1731500000 };

function can(role: Role): string {
  return role === "admin" ? "full access" : "read only";
}

console.log(`${user.id}: ${user.email}`);
console.log(`${auditor.id} lastSeen=${auditor.lastSeen}`);
console.log(can("admin"), can("viewer"));
// 同名 interface 会自动合并成员(declaration merging);type 重复声明则直接报错

How the code works

Interfaces Extend While Type Unions Compose is built around the function can.

Caveats

  • Self-contained — no imports beyond what the runtime already provides.

Using it

Signature: function can(role: Role)

Key statements

return role === "admin" ? "full access" : "read only";

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `can` at load time.