Pattern Matching
match is a native tyrus control-flow form that checks whether every possible case is handled.
Arms use pattern => body directly. For a single returned expression, use the compact form pattern => expression;; its semicolon is required. Block arms remain supported, and their trailing semicolon is optional. Parentheses around a pattern are optional for every supported pattern, so both "ready" => and ("ready") => are equivalent.
function label(score: i32): string {
match (score) {
90..=100 => "A";
_ => { return "F"; }
}
}A compact arm is a return
pattern => expression; returns expression from the enclosing function, exactly like return expression;. Inside a loop it therefore leaves the whole function, not just the loop, and nothing after the match runs. The program below prints only one. To run the arm and continue, use a block arm, 1 => { print("one"); }.
const main = (): void => {
const codes: i32[] = [1, 2, 3];
for (const code of codes) {
match (code) {
1 => print("one"); // returns from `main`
_ => { print("other"); } // continues after the `match`
}
print("next");
}
print("done");
};Match over Unions
type Result =
| { tag: "success"; data: string }
| { tag: "error"; code: i32; message: string };
const res: Result = { tag: "error", code: 404, message: "Not Found" };
match (res) {
{ tag: "success", data } => {
print(`Data: ${data}`); // "Data: ..."
}
({ tag: "error", code, message }) if (code === 404) => {
print(`Error specific 404: ${message}`); // "Error specific 404: Not Found"
}
{ tag: "error", message } => {
print(`Other error: ${message}`); // "Other error: ..."
}
_ => {
print("Unknown result");
}
}Supported patterns include literal matches, wildcard _, capture bindings, guarded arms, object destructuring with literal field matching, and array patterns.
Array Patterns
Array patterns destructure Array<T> and readonly Array<T> values. [] matches only an empty array, [first, second] matches exactly two elements, and [head, ...tail] matches one or more elements. Element bindings have type T; tail is a new owned Array<T> containing the remaining elements, equivalent to values.slice(1), rather than a borrowed view. An array pattern permits at most one rest pattern, it must be final, and it must be either a binding or _. Literal elements must be assignable to T. Nested array patterns and length-based exhaustiveness remain unavailable because ordinary arrays do not carry their length in the type.
function inspect(values: i32[]): void {
match (values) {
[] => { print("empty"); }
[value] => { print(value); }
[head, ...tail] => { print(head, tail.length); }
}
}Literal Matching
Match directly against constant values like strings, numbers, or booleans.
const day: string = "Monday";
match (day) {
("Saturday" | "Sunday") => {
print("Weekend");
}
("Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday") => {
print("Weekday");
}
_ => {
print("Invalid day");
}
}
// "Weekday"Range Patterns
Match a numeric or char value against a bounded interval: a..b excludes b, a..=b includes it, and either bound may be omitted for an open range (..b, a..). A range bound must be assignable to the subject's own type, matching a string against a numeric range is a compile error.
const main = (): void => {
const getLetterGrade = (score: u8): string => {
match (score) {
90..=100 => "A";
80..=89 => "B";
70..=79 => "C";
60..=69 => "D";
0..=59 => "F";
_ => "Invalid Score";
}
};
print(getLetterGrade(95)); // A
print(getLetterGrade(80)); // B
print(getLetterGrade(79)); // C
print(getLetterGrade(61)); // D
print(getLetterGrade(59)); // F
print(getLetterGrade(150)); // Invalid Score
};An empty or inverted range (10..5) is a warning, not an error, it simply never matches, the same as any other unreachable arm. Detecting overlapping arms and verifying exhaustiveness for a finite numeric type (u8, for example) are deliberate scope decisions, not gaps: both remain open, tracked refinements rather than required behavior.
Binding Patterns
Capture matched values into variables for use in the arm body.
type Shape =
| { kind: "circle"; radius: f64 }
| { kind: "rectangle"; width: f64; height: f64 };
const area = (shape: Shape): f64 => {
match (shape) {
({ kind: "circle", radius }) => {
return 3.14159 * radius * radius;
}
({ kind: "rectangle", width, height }) => {
return width * height;
}
}
};
const circle: Shape = { kind: "circle", radius: 5.0 };
print(area(circle)); // 78.53975Wildcard Pattern
Use _ to match any value that wasn't matched by previous arms.
const status: i32 = 200;
match (status) {
(200) => {
print("OK");
}
404 => {
print("Not Found");
}
(500) => {
print("Server Error");
}
_ => {
print(`Other status: ${status}`);
}
}
// "OK"Guarded Arms
Add if conditions to arms for more specific matching.
const value: i32 = 15;
match (value) {
(v) if (v < 0) => {
print("Negative");
}
0 => {
print("Zero");
}
(v) if (v % 2 === 0) => {
print("Positive even");
}
_ => {
print("Positive odd");
}
}
// Positive oddObject Destructuring
Destructure objects and match against specific field values.
interface Point {
x: f64;
y: f64;
}
const describe = (point: Point): string => {
match (point) {
({ x: 0, y: 0 }) => {
return "Origin";
}
({ x: 0, y }) => {
return `On Y-axis at ${y}`;
}
({ x, y: 0 }) => {
return `On X-axis at ${x}`;
}
({ x, y }) => {
return `Point at (${x}, ${y})`;
}
}
};
print(describe({ x: 0, y: 5 })); // "On Y-axis at 5"
print(describe({ x: 3, y: 0 })); // "On X-axis at 3"
print(describe({ x: 1, y: 2 })); // "Point at (1, 2)"Combined Patterns
Combine type narrowing, guards, and literal matching for complex logic.
type Input =
| string
| number
| boolean;
const process = (input: Input): string => {
match (input) {
(s: string) if (s.length === 0) => {
return "Empty string";
}
(s: string) => {
return `String: ${s}`;
}
(n: number) if (n < 0) => {
return "Negative number";
}
(n: number) if (n === 0) => {
return "Zero";
}
(n: number) => {
return `Positive number: ${n}`;
}
(true) => {
return "Boolean true";
}
(false) => {
return "Boolean false";
}
}
};
print(process("hello")); // "String: hello"
print(process("")); // "Empty string"
print(process(-5)); // "Negative number"
print(process(0)); // "Zero"
print(process(42)); // "Positive number: 42"
print(process(true)); // "Boolean true"Enum Variant Patterns
Match an algebraic enum by variant and bind one name per payload field. A variant with two fields needs two bindings: a single name for a multi-field payload is rejected, because there is no way to read the fields back out of it. A variant without a payload takes no binding at all.
import { PI } from "tyrus:math";
enum Shape {
Circle(f64),
Rect(f64, f64),
Empty,
}
const area = (shape: Shape): f64 => {
match (shape) {
Shape.Circle(r) => PI * r * r;
Shape.Rect(w, h) => w * h;
Shape.Empty => 0.0;
}
};
print(area(Shape.Circle(2.0))); // 12.566370614359172
print(`${area(Shape.Circle(2.0)):.2f}`); // 12.57
print(area(Shape.Rect(3.0, 4.0))); // 12.0
print(area(Shape.Empty)); // 0.0Exhaustiveness
For closed subjects such as enum, boolean, literal union and tagged union values, match should cover every variant or include _. Unreachable arms are reported as warnings.
Switch is covered in Control Flow
Use switch for literal dispatch over primitive values. Use match when destructuring, narrowing or exhaustiveness matters.
