Example
classDiagram
class Diagram {
+String id
+String code
+String r2_key
+Int view_count
+save()
+share() String
}
class User {
+String id
+String email
+String plan
+getDiagrams() Diagram[]
}
User "1" --> "many" Diagram : owns Syntax
Classes and members
classDiagram
class Order {
+String id
-Money total
#List~Item~ items
+addItem(Item item) void
+total() Money
} Prefixes: + public, - private, # protected, ~ package. Generics use tildes: List~Item~ renders as List<Item>.
Relationships
classDiagram
Animal <|-- Dog : inheritance
Car *-- Engine : composition
Team o-- Player : aggregation
Client --> Server : association
Client ..> Logger : dependency
Shape <|.. Circle : realization The arrowhead points at the parent, whole, or target. Read <|-- as "is-a", *-- as "owns", o-- as "has".
Cardinality
classDiagram
Customer "1" --> "0..*" Order : places
Order "1" *-- "1..*" LineItem Quoted strings on either side of the arrow; use 1, 0..1, 1..*, *, or n.
Annotations
classDiagram
class Repository {
<<interface>>
+find(id) Entity
}
class Status {
<<enumeration>>
ACTIVE
ARCHIVED
} Stereotypes <<interface>>, <<abstract>>, <<service>>, <<enumeration>> render above the class name.
Common mistakes
These are the parse errors that come up most, including in code written by ChatGPT and Claude. Paste any failing diagram into the editor and it marks the offending line.
-
Angle brackets for generics:
List<Item> items.Fix: Mermaid uses tildes:
List~Item~ items. Angle brackets collide with the arrow tokens. -
Method parameters with spaces and no parentheses on the return type:
+save(Order order): void.Fix: Return type goes after the closing parenthesis with a space, no colon:
+save(Order order) void. -
Relationship arrow drawn in the wrong direction, e.g.
Dog <|-- Animal.Fix: The open triangle sits on the parent:
Animal <|-- Dog. Read the arrow as "Animal is extended by Dog".
Real-world examples
Complete, copy-ready class diagrams for common situations. Each one opens in the editor with a click.
-
MVC Pattern Class Diagram: Model, View, Controller
Mermaid class diagram of the Model-View-Controller pattern for a task list app: fields, methods, generics, and association, dependency, and aggregation arrows.
-
Observer Pattern Class Diagram with Interfaces
Mermaid class diagram of the Observer pattern: Subject and Observer interfaces, a concrete StockTicker subject, two concrete observers, and realization arrows.
FAQ
Can I namespace classes?
Yes: wrap them in namespace Billing { class Invoice ... }. Classes inside render in a labelled box, and you can still draw relationships across namespaces.
How do I link a class to its source file?
link Order "https://github.com/org/repo/blob/main/order.ts" makes the class name clickable in renderers that allow links. GitHub's renderer strips them.