Skip to content

Operators and Expressions ​

Tyrus keeps familiar operators where the semantics can be checked statically and lowered to native code.

Operator Groups ​

CategoryOperators
Arithmetic+ - * / % **
Unary- + ++ -- ! not ~
Bitwise& | ^ ~ << >> >>>
Comparison> < >= <= === !==
Logical&& and || or
Ternary? :
Assignment= += -= *= /= %= **= &= |= ^= <<= >>= >>>= &&= ||= ??=
Null safety?? ?.
Borrow& &mut
Membershipin not in
Type checkis not is
Range.. ..=

and, or, and not are exact written equivalents of &&, ||, and !, the lexer maps each pair to the same token, so both spellings can be mixed freely in the same expression: active and not suspended or isAdmin and active && !suspended || isAdmin compile identically.

Chained Comparisons ​

Three or more of <, <=, >, >=, === chained directly (a < b < c) are sugar for a < b && b < c, reading closer to algebraic notation than the equivalent written with &&.

tyrus
const temp: u32 = 25;
print(0 < temp < 100); // true

const age: i32 = 25;
print(18 <= age < 65); // true

const getValue = (): i32 => 25;
print(10 < getValue() <= 50); // true - getValue() runs once, not twice

Each term in the chain is evaluated exactly once, even when it takes part in two comparisons, a term with a side effect (a function call) never runs twice. The chain also short-circuits like &&: once one comparison fails, later terms are never evaluated. Two terms (a < b) are unaffected by this sugar and stay a plain comparison; the chain only applies at three terms or more. !== never chains, there is no algebraic reading of a != b != c, so it always stays a plain, two-term comparison.

Pipeline ​

See the Pipe Operator guide for the |> operator, the % topic token, and pipeline composition.

Ternary ​

tyrus
const label: string = score >= 90 ? "A" : "B";

The ternary condition must be boolean and both branches must have the same type.

typeof ​

The typeof operator returns a string naming the tyrus type of a value at runtime. Numeric types stay distinct instead of collapsing to a general number category, an array reports its element type, an interface reports its name, and an optional keeps its ?. Only two shapes answer with a category, because they have no name to give: an anonymous object type ("object") and a function (`"function").

tyrus
const t1: string = typeof 42;        // "i32"
const t2: string = typeof "hello";   // "string"
const t3: string = typeof true;      // "boolean"
const t4: string = typeof [1, 2];    // "i32[]"
const t5: string = typeof 3.14;      // "f64"
const t6: string = typeof 12.50d;    // "decimal"

typeof can also be used as a type query.

tyrus
const count: i32 = 42;
type CountType = typeof count;
const other: CountType = 7;

typeof comparisons narrow union values in control flow.

tyrus
function describeValue(value: string | i32): void {
    if (typeof value === "string") {
        print(value.length); // string length
    } else if (typeof value === "i32") {
        print(value + 1); // value + 1
    }
}

This works with enums as well, typeof returns the underlying representation:

tyrus
enum Status: string {
    Active = "active",
    Inactive = "inactive",
}

const current: Status = Status.Active;
const kind: string = typeof current; // "string", the enum's backing type

is / not is ​

The is operator checks whether a runtime value matches a specific type within a union, returning boolean. It is the primary mechanism for type narrowing on union types.

tyrus
function process(value: string | number): void {
    if (value is string) {
        print(value.length); // string length
    } else {
        print(value + 1); // number
    }
}

Inside the true branch, the compiler narrows value to string. Outside, it remains string | number.

not is is the negated form:

tyrus
function handle(value: string | number): void {
    if (value not is string) {
        print(value + 1); // number
    } else {
        print(value.length); // string
    }
}

is/not is also work in while conditions and boolean assignments. The check runs at runtime by comparing the union's type tag against the target type.

A caught error keeps the type it was thrown as, so is also tells errors apart. In catch (error), error is ConfigError is true when the value thrown was a ConfigError (a module error such as FsError, or an interface that extends Error), and inside that branch error has every field of the subtype. A catch (error: A | B) narrows to the variant the same way. This holds in an async function too, including for an error that arrives as a rejected await, and in a catch (error) that awaits before checking. Only an Error that did not come from a catch cannot tell its subtype (E3297). A handler that checks for the errors it knows ends with throw error; for the rest: the value goes on with its subtype, so the next catch still tells it apart, and an error type added later is passed on instead of silenced.

tyrus
import { FsError, readFileSync } from "tyrus:fs";

interface ConfigError extends Error {
    path: string;
}

function readText(path: string): string throws FsError {
    let contents: string = "";
    match (readFileSync(path)) {
        Ok(text) => { contents = text; }
        Err(error) => { throw error; }
    }
    return contents;
}

function loadConfig(path: string): string throws ConfigError {
    const failure: ConfigError = { message: "config is missing", code: "ERR_CONFIG", path: path };
    throw failure;
}

function readSettings(): string throws Error {
    try {
        return readText("settings.json") + loadConfig("app.json");
    } catch (error) {
        if (error is ConfigError) {
            console.error(`${error.code}: ${error.path}`);
            return "";
        }
        // What this handler does not recognize goes on, subtype and all.
        throw error;
    }
}

const main = (): void => {
    try {
        console.log(readSettings());
    } catch (error) {
        if (error is FsError) {
            console.error(`${error.code}: ${error.message}`);
        } else {
            console.error(error.message);
        }
    }
};

Type Assertions ​

tyrus
const value: i32 = 42;
const converted: f64 = value as f64;
const narrowed: u32 = 4294967295 as u32;

A numeric assertion preserves the value or aborts; it never wraps. The checks run in every profile, so a debug run predicts what the shipped binary does. Non-primitive assertions are identity casts and should be used carefully.

Conversion and Parsing ​

tyrus
const label: string = (42).toString();
const flag: string = String(true);
const parsedCount: i64? = parseInt("42 items");
const ratio: f64? = parseFloat("3.5e2!");
const strict: f64? = Number("2.5abc");

Parsing returns optional values instead of NaN, preserving null safety.

The annotation picks the numeric width used by the parse. parseInt narrows to any integer type and parseFloat/Number to f32 or f64; with no annotation they stay i64? and f64?. Text whose value does not fit the target simply does not parse as that type, so the result is absence rather than a truncated value.

tyrus
const port: i32? = parseInt("8080");
const overflowed: i32? = parseInt("9999999999");
const count: u32? = parseInt("-5");
const single: f32? = parseFloat("3.5");

A plain as T preserves the value or aborts; it never wraps around. What fits depends on the bounds of both types rather than on their widths, so a u32 holds a value above i32::MAX while a negative number never fits a u32, not even one of the same width.

as T? is a fallible cast and follows the same rule, except that a value outside the range of T becomes absence instead of aborting, which is how a program recovers from one. A cast from a float to an integer truncates toward zero, and NaN yields absence.

tyrus
const wide: i64 = 9999999999;
const narrowed = wide as i32?;                  // empty, does not fit an i32
const fits = 7 as i32?;                         // 7
const truncated = parseFloat("2.9") as i32?;    // 2
const unbounded = parseFloat("1e30") as i32?;   // empty

as converts between numbers; it never reinterprets a value as an unrelated type. An enum reads back as the primitive it is represented by, but nothing else crosses: a string is not a number, and one interface is not another even when their fields line up. A value of the target type has to be built, and asserting it instead is an error.

error

tyrus
interface Loose {
    age: i32;
}

interface User {
    @min(18)
    age: i32;
}

const loose: Loose = { age: 1 };
const user: User = loose as User;   

error

text
error[E0605]: cannot convert `Loose` to `User` with `as`: `as` converts, it does not reinterpret: a `Loose` value is not a `User`
at /src/main.tyr:11:20
const user: User = loose as User;
                   ^^^^^
help: build the target value from the source instead of asserting it, or annotate the value with the target type where it is created

This matters most where a type carries validators. A User is guaranteed to satisfy @min(18), and that guarantee is what lets the rest of the program skip the check. A conversion that produced a User without running its validators would make the guarantee a lie, so it is rejected: build the User, and handle the ValidationError it may throw.

Spread and Rest ​

The spread operator expands arrays and objects into individual elements or fields:

tyrus
const first: i32[] = [1, 2, 3];
const second: i32[] = [4, 5, 6];
const merged: i32[] = [...first, ...second];

interface Config {
    host: string;
    port: i32;
}

const base: Config = { host: "localhost", port: 8080 };
const overrides: Partial<Config> = { port: 3000 };
const merged_config: Config = { ...base, ...overrides };

Rest parameters collect trailing arguments into an array:

tyrus
const log = (level: string, ...messages: string[]): void => {
    for (const msg of messages) {
        print(`[${level}] ${msg}`); // "[info] server started", "[info] listening on port 3000"
    }
};

log("info", "server started", "listening on port 3000");

Membership and Ranges ​

in and not in check whether a value belongs to an array, a Range, a Map, or a Set, replacing .includes()/!.includes() and .has()/!.has() calls. not in is the negated form, spelled with the not keyword rather than a separate operator.

a..b is a Range from a up to, but excluding, b; a..=b includes b. A range can be annotated as Range<T>, such as const ids: Range<i32> = 1..4;. A Range has its own .contains(x) method, x in a..b and (a..b).contains(x) are the same check.

tyrus
const permissions: string[] = ["admin", "editor", "dev"];
print("admin" in permissions);
// true
print("guest" not in permissions);
// true

const status: i32 = 204;
print(status in 200..299);
// true
print(status not in 400..=599);
// true

const httpOk = 200..299;
print(httpOk.contains(204));
// true

in/not in also keep their original meaning over a plain object or interface value: "field" in obj checks whether obj's type declares a field named "field", independent of the array/Range/Map/Set membership check above.