Skip to content

Objects and Interfaces ​

Tyrus uses concise object syntax, while named interfaces and object aliases lower to native struct layouts.

Interfaces ​

tyrus
interface User {
    readonly id: i32;
    name: string;
    nickname?: string;
    active: boolean;
}

const user: User = {
    id: 1,
    name: "Ada",
    active: true,
};

const renamed: User = {
    ...user,
    name: "Grace",
};

const active: boolean = true;
const shorthand: User = { id: 2, name: "Grace", active };

readonly prevents field reassignment. Optional fields read as T? and must be handled with narrowing or ??. Object literals are checked for missing, extra and incorrectly typed fields. Object spread creates immutable updates with the same interface layout as the source object. When a field's value is a local variable with the same name, write the name once, { active } is shorthand for { active: active }, and mixes freely with explicit key: value fields and with a spread update.

Automatic Data Methods ​

Every named data interface receives automatic data methods without annotations or declarations. The first four are regular instance calls, and fromJson is a static call on the concrete interface name. A behavior interface can define an instance method with the same name and takes precedence over the automatic method.

copy() ​

Creates an independent structural copy.

copy() is not only for objects: it exists on every value that owns a buffer, which is every type that is not Copy. That covers string, arrays, tuples, and the optionals, results and unions built from them. On a Copy scalar such as i32 there is no method, because let a = b already duplicates one and a method would suggest something else happens.

The result is a plain value of its own type. A decoration belongs to the field a value was read from, not to the value, so nothing about the source's declaration follows the copy.

Reading a field into a binding of the same type moves it: const items = order.items; hands the field to items, order stays usable through its other fields, and reading order.items or order as a whole afterwards is refused (E0382) until the field is assigned again. Where a move cannot happen, the compiler suggests copy() instead: when the owner's fields carry validators, whose rules describe the value as a whole, when the field is reached through a reference, or when the binding is declared with a different type than the field, such as a string read out of a narrowed string? (E3081). order.items.copy() says what it does and keeps the cost visible, which a copy inserted silently would not.

tyrus
interface User { name: string; }

const user: User = { name: "Ada" };
const copied: User = user.copy();
print(copied); // { name: "Ada" }

equals(other: Type) ​

Compares eligible fields structurally, including absent and present optional fields. Arrays are not eligible because their equality is by address. The argument must have the same nominal interface type.

tyrus
interface User { name: string; }

const first: User = { name: "Ada" };
const second: User = { name: "Ada" };
const same: boolean = first.equals(second); // true

An interface with matching fields still cannot be passed to equals() when it has a different name:

error

tyrus
interface User { name: string; }
interface OtherUser { name: string; }

const main = (): void => {
    const user: User = { name: "Ada" };
    const other: OtherUser = { name: "Ada" };
    const same: boolean = user.equals(other); 
    print(same);
};
text
error[E0308]: `OtherUser` is not assignable to `User`: tyrus interfaces are nominal, so distinct interface names are separate types even with the same fields; build a `User` value directly (its fields are available on `OtherUser`), or use one shared interface type for both
at /src/main.tyr:7:27
    const same: boolean = user.equals(other);
                          ^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

toString() ​

Produces a readable representation in declared field order, quotes and escapes strings, renders absent optional fields as None, and recursively renders nested values.

tyrus
interface User { name: string; nickname?: string; }

const user: User = { name: "Ada" };
const text: string = user.toString(); // "{ name: \"Ada\", nickname: None }"

toJson(options?: { pretty: boolean }) ​

Encodes canonical JSON with a space after each colon. Pass { pretty: true } for multi-line JSON with four-space indentation. Keys are written in sorted order, not declaration order, so the same data always produces the same text: adding a field later does not move the ones already there. A decimal is written in plain notation, the same text it prints as: 12.50d is 12.5, with every digit preserved and no rounding.

tyrus
interface User { 
  name: string; 
  scores: i32[]; 
}

const user: User = { name: "Ada", scores: [10, 20] };
const json: string = user.toJson();
const pretty: string = user.toJson({
    pretty: true,
});

print(json); // {"name": "Ada","scores": [10,20]}
print(pretty);
/*
{
    "name": "Ada",
    "scores": [
        10,
        20
    ]
}
*/

A field holding a discriminated union is written as the object its live variant already is: there is no envelope, and the discriminant field is what tells a reader which variant it got. fromJson reads one back the same way, choosing the variant by its discriminant; a discriminant naming no declared variant is refused with ERR_JSON_UNKNOWN_VARIANT rather than guessed at, which is the whole reason for writing it.

tyrus
interface Job {
    id: i32;
    state: { kind: "done"; value: i32 } | { kind: "failed"; reason: string };
}

const done: Job = { id: 1, state: { kind: "done", value: 42 } };
console.log(done.toJson());
// {"id": 1,"state": {"kind": "done","value": 42}}

const failed: Job = { id: 2, state: { kind: "failed", reason: "timeout" } };
console.log(failed.toJson());
// {"id": 2,"state": {"kind": "failed","reason": "timeout"}}

Type.fromJson(text: string) ​

Validates syntax, fields, types and numeric ranges, returning JsonError with stable code, readable message, and field path instead of throwing.

Signatureinterface JsonError { readonly code: string; readonly message: string; readonly path: string; }
tyrus
interface User { name: string; }

const result: Result<User, JsonError> = User.fromJson("{\"name\":\"Ada\"}");
match (result) {
    Ok(user) => {
        print(user.name); // Ada
    }
    Err(error) => {
        printError(error.code);
    }
}

Use onfail to print a JsonError and stop the current void function when decoding fails:

error

tyrus
interface User { name: string; }

function main(): void {
    const json = User.fromJson("{\"name\":123}") onfail {
        print(json.code); // ERR_JSON_TYPE_MISMATCH
        print(json.message); // JSON field does not match the declared type
        print(json.path); // name
    };

    print(json.name); //
}

Behavior Interfaces with at ​

Behavior interfaces attach executable methods to one or more receiver types with at. The receiver is an explicit first parameter, so the method remains ordinary and its call-site syntax is value.method(). When its annotation is omitted for multiple targets, the compiler specializes and checks the implementation separately for every target. A behavior interface contains methods or shorthand bindings, not data fields.

tyrus
interface User {
    age: u32;
}

interface UserMethods at User {
    isAdult(user: User): boolean {
        return user.age >= 18;
    }
}

const user: User = { age: 21 };
const adult: boolean = user.isAdult(); // true
tyrus
// model.tyr
export interface User { age: u32; }
export const ageText = (user: User): string => user.age.toString();
export interface UserMethods at User { ageText; }

// main.tyr
import { User, UserMethods } from "./model";
const user: User = { age: 21 };
const text: string = user.ageText(); // "21"
tyrus
interface NumberMethods at i32 {
    isPositive(value: i32): boolean {
        return value > 0;
    }
}

interface StringMethods at string {
    isBlank(value: string): boolean {
        return value.length === 0;
    }
}

interface BooleanMethods at boolean {
    inverted(value: boolean): boolean {
        return !value;
    }
}

interface CharMethods at char {
    isAscii(value: char): boolean {
        return value.isAlphabetic();
    }
}

const number: i32 = 4;
const text: string = "";
const enabled: boolean = true;
const letter: char = 'A';
const positive: boolean = number.isPositive(); // true
const blank: boolean = text.isBlank(); // true
const inverted: boolean = enabled.inverted(); // false
const ascii: boolean = letter.isAscii(); // true
tyrus
interface PositiveNumbers at i32, u32 {
    isPositive(value): boolean {
        return value > 0;
    }
}

const signed: i32 = 7;
const unsigned: u32 = 9;
const signedPositive: boolean = signed.isPositive(); // true
const unsignedPositive: boolean = unsigned.isPositive(); // true

Shorthand bindings name functions declared in the same module or imported from another module. Their signatures are checked when the behavior is declared, and the imported signature is retained across module boundaries for type checking and native code generation. Behavior interfaces can also extend other behavior interfaces to inherit their methods.

The receiver of at may be a named interface or a primitive type. The same member-call syntax works for numeric values, strings, booleans and chars.

Property access by name ​

A field is read and written with the dot form, and with a string literal in brackets, the two are the same access: the key is written in the source, so it names a field the compiler knows, and both compile to the same fixed offset.

tyrus
interface Person {
    name: string;
    age: i32;
}

let person: Person = { name: "Ada", age: 36 };

print(person.name);
print(person["name"]);

person["age"] = 42;

Only a literal qualifies. person[key], where key is a variable, is a compile error (E0608): an interface has a fixed set of fields and no run-time lookup to fall back on. A literal that names no field is E0609, reported with the name. For keys decided at run time, use Record<string, T>, which is a real hash map, lookup["a"] there is a lookup that can miss, so it yields T?.

Field assignment ​

A field can be assigned in place with object.field = value, including compound forms such as +=, through nested receivers, and on indexed elements.

tyrus
interface Point {
    x: i64;
    y: i64;
}

let point: Point = { x: 1, y: 2 };
point.x = 10;
point.y += 5;

In-place assignment requires a mutable binding: a const binding is deeply immutable, and a readonly field or a value of a readonly type rejects the write. In-place assignment currently works for number, boolean and char fields; to change a string, an array or a nested object field, build a new value with object spread.

Interface Inheritance ​

An interface can extend one or more other interfaces to inherit their fields. The child interface requires every inherited field plus its own, so a value of the child type must provide all of them. Inheritance only merges fields, it does not make the child assignable to the parent (see the nominal layout below).

tyrus
interface Age {
    age: u32;
}

interface Person extends Age {
    name: string;
}

// `Person` requires both the inherited `age` and its own `name`.
const person: Person = { age: 30, name: "Ada" };

// An interface that extends another and adds nothing has just the inherited
// fields.
interface JustAge extends Age {}
const onlyAge: JustAge = { age: 25 };

Type Intersection ​

A type alias combines object types with &. The alias requires every field of every operand, exactly as inheritance does, and each operand is either a named interface or an object written inline. & is the alias form of what extend does for an interface: interface inherits with extend, type combines with &.

tyrus
interface Age {
    age: u32;
}

interface Contact {
    email: string;
}

// `&` combines object types into one named type.
type Person = Age & Contact;
const person: Person = { age: 30, email: "[email protected]" };

// An operand can be written inline, anywhere in the chain.
type Employee = { title: string; } & Age & Contact;
const employee: Employee = { title: "Engineer", age: 41, email: "[email protected]" };

When two operands declare the same field with different types, the alias is rejected where it is written (E3214) instead of producing a field no value can ever satisfy.

error

tyrus
interface Metric {
    value: i32;
}

interface Label {
    value: string;
}

type Mixed = Metric & Label; 

& belongs to a type alias and nowhere else. It is not accepted in a type annotation (E3215): name the intersection first, then use the name.

error

tyrus
interface Age {
    age: u32;
}

interface Contact {
    email: string;
}

function greet(person: Age & Contact): void { 
    print(person.email);
}

Every operand must be an object type. An operand that is a primitive, an array, a union or a function is rejected with E3213, and an alias that refers to itself through the chain is rejected with E3216. Mixing & and | in the same alias is rejected with E3217, which is its own diagnostic because the reason is the precedence: | binds tighter, so type A = B & C | D; would read as B & (C | D). Parentheses alone do not help, since a union is never a valid operand. Name the intersection and use that name in the union: type BC = B & C; and then type A = BC | D;.

Nominal Native Layout ​

Matching object shapes are not interchangeable. Interfaces are native named product types, so passing a CompleteUser where SummaryUser is expected requires an explicit conversion object.

tyrus
interface SummaryUser {
    id: i32;
}

interface CompleteUser {
    id: i32;
    name: string;
}

const complete: CompleteUser = { id: 99, name: "TitenQ" };
const summary: SummaryUser = { id: complete.id };

To hold values of several shapes in one collection, use a tagged union with a literal discriminant field and match instead of a shared base interface, it keeps every variant's fields and stays exhaustive:

tyrus
type User =
    | { kind: "admin"; name: string; permissions: string }
    | { kind: "guest"; name: string; expiresAt: i64 };

const nameOf = (user: User): string => {
    match (user) {
        ({ kind: "admin", name }) => { return name; }
        ({ kind: "guest", name }) => { return name; }
    }
    return "";
};

const users: User[] = [
    { kind: "admin", name: "Ada", permissions: "root" },
    { kind: "guest", name: "Bob", expiresAt: 999 },
];

Field Storage Order ​

Fields are stored in whatever order wastes the least space, which is not always the order they are written: a wide field is placed ahead of a narrow one so the gap the narrow one would leave in front of it disappears. The interface below is 40 bytes written this way and 24 bytes as stored, and holding a million of them is the difference between 40 MB and 24 MB.

tyrus
interface Reading {
    ok: boolean;
    id: i64;
    scale: u8;
    value: f64;
    stale: boolean;
    sequence: i32;
}

const reading: Reading = {
    ok: true,
    id: 900000000001,
    scale: 4,
    value: 2.5,
    stale: false,
    sequence: 77,
};

Nothing about using the interface changes: fields are read, written, spread and destructured by name, an object literal still evaluates its fields in the order it lists them, and printing a value still shows the fields in the order the interface declares them. The order is a storage decision and is never observable from the program.

Type Aliases ​

tyrus
type Point = {
    x: i32;
    y: i32;
};

For object shapes, type and interface are equivalent in native layout. A type alias can also name unions, tuples, function types and utility types.

Type Utilities ​

CategoryUtilities
Object transformationPartial<T>, Optional<T, K>, Required<T>, Readonly<T>, DeepPartial<T>
Key selectionPick<T, K>, Omit<T, K>
Type-based selectionPickByType<T, Type>, OmitByType<T, Type>
Key renamingCamelCaseKeys<T>, SnakeCaseKeys<T>
Field controlRequire<T, K>, AtLeastOne<T, K>
Data extractionDataOnly<T>
Key/value mappingkeyof, Record<K, T>
Function typesReturnType<T>, Parameters<T>
Union manipulationExclude<T, U>, Extract<T, U>
Conditional typesT extends U ? X : Y, infer R

Object transformation ​

Partial<T> ​

Makes every field optional, the caller can provide any subset.

SignaturePartial<T> = { [K in keyof T]?: T[K] }
tyrus
interface Account {
    id: i32;
    email: string;
    active: boolean;
}

type AccountPatch = Partial<Account>;
const patch: AccountPatch = { email: "[email protected]" };

error

tyrus
interface Account {
    id: i32;
    email: string;
    active: boolean;
}

type AccountPatch = Partial<Account>;
const patch: AccountPatch = { email: 42 }; 
text
error[E0308]: type mismatch for `email`: expected `string?`, found `42`
at /src/main.tyr:8:31
const patch: AccountPatch = { email: 42 };
                              ^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Optional<T, K> ​

Keeps every field and makes only the selected keys optional. The existing one-argument form, Optional<T>, remains the spelling for T?.

SignatureOptional<T, K extends keyof T> = { [P in keyof T]: P extends K ? T[P]? : T[P] }
tyrus
interface User {
    id: i32;
    name: string;
    email?: string;
    password: string;
}

type Update = Optional<User, "name" | "email">;
const update: Update = { id: 1, password: "rotated" };

const user: User = { id: 1, name: "Ada", password: "secret" };
const publicUser = user.pick(["id", "name"]);
const storedUser = user.omit(["password"]);

print(publicUser.name);
print(storedUser.id);

Required<T> ​

Turns every optional field into a mandatory one, all fields must be provided.

SignatureRequired<T> = { [K in keyof T]-?: T[K] }
tyrus
interface Config {
    host?: string;
    port?: i32;
}

type StrictConfig = Required<Config>;
const cfg: StrictConfig = { host: "localhost", port: 8080 };

error

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

type StrictConfig = Required<Config>;
const cfg: StrictConfig = { host: "localhost" }; 
text
error[E2741]: property `port` is missing in object literal for type `object`
at /src/main.tyr:7:7
const cfg: StrictConfig = { host: "localhost" };
      ^^^

Readonly<T> ​

Prevents field reassignment, the entire object becomes deeply immutable. It is one of six places the keyword appears; the Readonly page covers them all.

SignatureReadonly<T> = { readonly [K in keyof T]: Readonly<T[K]> }
tyrus
interface Endpoint {
    port: i32;
}

interface Config {
    endpoint: Endpoint;
    name: string;
}

type Frozen = Readonly<Config>;

export function main(): void {
    let config: Frozen = { endpoint: { port: 8080 }, name: "api" };
    print(config.endpoint.port);
}

error

tyrus
let config: Frozen = { endpoint: { port: 8080 }, name: "api" };
config.name = "web"; 
text
error[E2542]: cannot assign to readonly property `name`
at /src/main.tyr:18:1
config.name = "web";
^^^^^^^^^^^^^^^^^^^^

The guarantee reaches every level, not only the surface. A nested object is frozen too:

error

tyrus
let config: Frozen = { endpoint: { port: 8080 }, name: "api" };
config.endpoint.port = 9090; 
text
error[E2541]: cannot assign to `port` through a readonly value
at /src/main.tyr:18:1
config.endpoint.port = 9090;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

An array field becomes a readonly array, so its mutating methods are refused as well:

error

tyrus
interface Tagged {
    tags: string[];
}

let tagged: Readonly<Tagged> = { tags: ["a"] };
tagged.tags.push("b"); 
text
error[E2540]: cannot call mutating method `push` on readonly array
at /src/main.tyr:6:1
tagged.tags.push("b");
^^^^^^^^^^^

Deeply recursive

Readonly<T> applies recursively to nested objects and arrays, so values cannot be mutated through a nested property.

The examples above use let. With const the binding is already deeply immutable on its own, so the rejection would come from the binding rather than from the type, and would not show what Readonly<T> adds.

DeepPartial<T> ​

Makes every field optional recursively, up to 5 levels deep. Ideal for partial update payloads (PATCH).

SignatureDeepPartial<T> = { [K in keyof T]?: DeepPartial<T[K]> }
tyrus
interface Config {
    db: {
        host: string;
        port: i32;
    };
    active: boolean;
}

type ConfigPatch = DeepPartial<Config>;
const patch: ConfigPatch = {
    db: {
        host: "localhost"
    }
};

error

tyrus
interface Config {
    db: {
        host: string;
        port: i32;
    };
    active: boolean;
}

type ConfigPatch = DeepPartial<Config>;
const bad: ConfigPatch = { db: { host: 42 } }; 
text
error[E0308]: type mismatch for `db`: expected `{ host?: string; port?: i32 }?`, found `object`
at /src/main.tyr:10:28
const bad: ConfigPatch = { db: { host: 42 } };
                           ^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Key selection ​

Pick<T, K> ​

Selects a subset of fields by key, the result has only the listed keys.

SignaturePick<T, K extends keyof T> = { [P in K]: T[P] }
tyrus
interface User {
    id: i32;
    name: string;
    email: string;
    role: string;
}

type UserSummary = Pick<User, "id" | "name">;
const summary: UserSummary = { id: 1, name: "Ada" };

error

tyrus
interface User {
    id: i32;
    name: string;
    email: string;
}

type Bad = Pick<User, "id" | "missing">; 
text
error[utility-unknown-key]: `missing` is not a property of the type given to `Pick`
at /src/main.tyr:1:1
interface User {
^

Omit<T, K> ​

Removes a subset of fields by key, the result has everything except the listed keys.

SignatureOmit<T, K extends keyof T> = { [P in Exclude<keyof T, K>]: T[P] }
tyrus
interface User {
    id: i32;
    name: string;
    email: string;
}

type PublicUser = Omit<User, "email">;
const pub: PublicUser = { id: 1, name: "Ada" };
tyrus
interface User {
    id: i32;
    name: string;
    email: string;
}

type PublicUser = Omit<User, "email">;
const email = pub.email; 
text
error[E0411]: field `email` does not exist on `PublicUser`
  --> src/main.tyr:6:21
   |
 6 | const email = pub.email;
   |                     ^^^^^ field `email` was omitted from the original type
   |
help: use the original `User` type if `email` is needed

Value projections ​

value.pick(keys) and value.omit(keys) create a new object with the selected or remaining fields. Keys must be known at compile time, either in an array literal or in a variable with a finite literal-key type. The receiver is not mutated, field order follows the source type, and there is no runtime key lookup.

tyrus
interface User {
    id: i32;
    name: string;
    email?: string;
    password: string;
}

type Update = Optional<User, "name" | "email">;
const update: Update = { id: 1, password: "rotated" };

const user: User = { id: 1, name: "Ada", password: "secret" };
const publicUser = user.pick(["id", "name"]);
const storedUser = user.omit(["password"]);

print(publicUser.name);
print(storedUser.id);

Type-based selection ​

PickByType<T, Type> ​

Selects fields by their value type, keeps only the fields whose type matches Type.

SignaturePickByType<T, Type> = { [K in keyof T as T[K] extends Type ? K : never]: T[K] }
tyrus
interface User {
    id: i32;
    name: string;
    email: string;
    active: boolean;
}

type UserStrings = PickByType<User, string>;
const preview: UserStrings = { name: "Ada", email: "[email protected]" };

error

tyrus
interface User {
    id: i32;
    name: string;
    email: string;
}

type UserId = PickByType<User, i32>;
const bad: UserId = { name: "Ada" }; 
text
error[E2353]: object literal specifies unknown property `name`
at /src/main.tyr:8:23
const bad: UserId = { name: "Ada" };
                      ^^^^

OmitByType<T, Type> ​

Removes fields by their value type, excludes all fields whose type matches Type.

SignatureOmitByType<T, Type> = { [K in keyof T as T[K] extends Type ? never : K]: T[K] }
tyrus
interface Product {
    id: i32;
    name: string;
    price: f64;
    inStock: boolean;
}

type NonNumeric = OmitByType<Product, i32>;
const listing: NonNumeric = { name: "Widget", price: 29.99, inStock: true };

error

tyrus
interface User {
    id: i32;
    name: string;
    email: string;
}

type UserData = OmitByType<User, string>;
const bad: UserData = { name: "Ada" }; 
text
error[E2353]: object literal specifies unknown property `name`
at /src/main.tyr:8:25
const bad: UserData = { name: "Ada" };
                        ^^^^

Key/value mapping ​

keyof ​

Extracts the keys of a type as a string literal union.

Signaturekeyof T = string literal union of T's keys
tyrus
interface Account {
    id: i32;
    email: string;
}

type Key = keyof Account;
const k: Key = "id";

error

tyrus
interface Account {
    id: i32;
    email: string;
}

type Key = keyof Account;
const k: Key = "missing"; 
text
error[E0308]: type mismatch for `k`: expected `"id" | "email"`, found `string`
at /src/main.tyr:7:7
const k: Key = "missing";
      ^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Record<K, T> ​

Record<K, T> is a built-in type utility, like Pick<T, K> and Omit<T, K>. It is resolved by the compiler and does not create a runtime Record class. When K is a finite union of string literal keys, Tyrus produces an object type with one required field per key. When K is open, such as string, Tyrus resolves it to Map<K, T> for dynamic keys.

SignatureRecord<K extends string, T> = required object fields for finite literal K; Map<K, T> for open K
tyrus
type Roles = Record<"admin" | "user", boolean>;
const perms: Roles = { admin: true, user: false };

error

tyrus
type Roles = Record<"admin" | "user", boolean>;
const perms: Roles = { admin: true }; 
text
error[E2741]: property `user` is missing in object literal for type `object`
at /src/main.tyr:2:7
const perms: Roles = { admin: true };
      ^^^^^

For an open key type, Record<string, T> resolves to Map<string, T>, so lookups may be absent and map methods are available:

tyrus
let inventory: Record<string, i32> = { apples: 3, pears: 5 };
inventory["bananas"] = 12;
const apples: i32 = inventory.get("apples") ?? 0;
const hasPears: boolean = inventory.has("pears");

Key renaming ​

CamelCaseKeys<T> ​

Transforms all snake_case field names to camelCase. Essential for integrating with external APIs.

SignatureCamelCaseKeys<T> = { [K in camelCase<keyof T>]: T[snake_case<K>] }
tyrus
interface ApiUser {
    user_id: i32;
    first_name: string;
    is_active: boolean;
}

type User = CamelCaseKeys<ApiUser>;
const user: User = { userId: 1, firstName: "Ada", isActive: true };

error

tyrus
interface Config {
    db_host: string;
    db_port: i32;
}

type Cfg = CamelCaseKeys<Config>;
const bad: Cfg = { db_host: "localhost", db_port: 5432 }; 
text
error[E2353]: object literal specifies unknown property `db_host`
at /src/main.tyr:7:20
const bad: Cfg = { db_host: "localhost", db_port: 5432 };
                   ^^^^^^^

SnakeCaseKeys<T> ​

Transforms all camelCase field names to snake_case. Useful for legacy API payloads and databases.

SignatureSnakeCaseKeys<T> = { [K in snake_case<keyof T>]: T[camelCase<K>] }
tyrus
interface User {
    userId: i32;
    firstName: string;
    isActive: boolean;
}

type UserDb = SnakeCaseKeys<User>;
const row: UserDb = { user_id: 1, first_name: "Ada", is_active: true };

error

tyrus
interface ApiConfig {
    dbHost: string;
    dbPort: i32;
}

type Legacy = SnakeCaseKeys<ApiConfig>;
const bad: Legacy = { dbHost: "localhost", dbPort: 5432 }; 
text
error[E2353]: object literal specifies unknown property `dbHost`
at /src/main.tyr:7:23
const bad: Legacy = { dbHost: "localhost", dbPort: 5432 };
                      ^^^^^^

Function types ​

ReturnType<T> ​

Infers the return type of a function type, extracts what the function produces.

SignatureReturnType<T extends (...args: any) => any> = T's return type
tyrus
type Fn = (i32) => string;
type Result = ReturnType<Fn>; // string

error

tyrus
type NotFn = i32;
type Bad = ReturnType<NotFn>; 
text
error[utility-non-function]: `ReturnType` requires a function type, found `i32`
at /src/main.tyr:1:1
type NotFn = i32;
^

Parameters<T> ​

Infers the parameter types of a function type as a tuple, extracts what the function expects.

SignatureParameters<T extends (...args: any) => any> = T's parameter tuple
tyrus
type Fn = (i32, string) => boolean;
type Params = Parameters<Fn>;

error

tyrus
type NotFn = i32;
type Bad = Parameters<NotFn>; 
text
error[utility-non-function]: `Parameters` requires a function type, found `i32`
at /src/main.tyr:1:1
type NotFn = i32;
^

Field control ​

Require<T, K> ​

Makes specific optional fields required. A noop if the field is already required.

SignatureRequire<T, K extends keyof T> = T & { [P in K]-?: T[P] }
tyrus
interface Client {
    id: i32;
    name: string;
    email?: string;
    phone?: string;
}

type ClientWithEmail = Require<Client, "email">;
const client: ClientWithEmail = { id: 1, name: "Ada", email: "[email protected]" };

error

tyrus
interface User {
    id: i32;
    name: string;
    email: string;
}

type Strict = Partial<User> & Require<User, "id">;
const bad: Strict = { name: "Ada" }; 
text
error[E0401]: missing required field `id`
  --> src/main.tyr:7:24
   |
 7 | const bad: Strict = { name: "Ada" };
   |                        ^^^^^^^^^^^^^^ field `id` is required by `Require<User, "id">`
   |
help: add `id` to the object literal

AtLeastOne<T, K> ​

Makes all specified fields optional but requires at least one of them to be present. Every key in K must be a property of T.

SignatureAtLeastOne<T, K extends keyof T> = { [P in keyof T]: P extends K ? T[P]? : T[P] }
tyrus
interface Form {
    name: string;
    email?: string;
    phone?: string;
}

type ContactForm = AtLeastOne<Form, "email" | "phone">;
const formA: ContactForm = { name: "Ada", email: "[email protected]" };
const formB: ContactForm = { name: "Ada", phone: "555-1234" };

error

tyrus
interface User {
    id: i32;
    name: string;
    email: string;
}

type Lookup = AtLeastOne<User, "name" | "email">;
const bad: Lookup = { id: 1 }; 
text
error[E0308]: type mismatch for `bad`: expected `{ id: i32; name: string; email?: string } | { id: i32; name?: string; email: string }`, found `object`
at /src/main.tyr:8:7
const bad: Lookup = { id: 1 };
      ^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Data extraction ​

DataOnly<T> ​

Removes all function-typed fields, keeping only pure data properties. Ideal for API payloads.

SignatureDataOnly<T> = { [K in keyof T as T[K] extends Function ? never : K]: T[K] }
tyrus
interface UserService {
    id: i32;
    name: string;
    save: () => boolean;
    notify: (string) => void;
}

type UserData = DataOnly<UserService>;
const data: UserData = { id: 1, name: "Ada" };

error

tyrus
interface ApiPayload {
    id: i32;
    name: string;
    validate: () => boolean;
}

type Data = DataOnly<ApiPayload>;
const bad: Data = { id: 1, name: "Ada", validate: () => true }; 
text
error[E2353]: object literal specifies unknown property `validate`
at /src/main.tyr:8:41
const bad: Data = { id: 1, name: "Ada", validate: () => true };
                                        ^^^^^^^^

Union manipulation ​

Exclude<T, U> ​

Removes members of U from T, keeps everything in T that is not in U.

SignatureExclude<T, U> = T extends U ? never : T
tyrus
type T = Exclude<"a" | "b" | "c", "a">;
const v: T = "b";

error

tyrus
type T = Exclude<"a" | "b" | "c", "a">;
const v: T = "a"; 
text
error[E0308]: type mismatch for `v`: expected `"b" | "c"`, found `string`
at /src/main.tyr:2:7
const v: T = "a";
      ^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Extract<T, U> ​

Keeps only members of T that also belong to U, computes the intersection.

SignatureExtract<T, U> = T extends U ? T : never
tyrus
type T = Extract<"a" | "b" | "c", "a" | "b">;
const v: T = "a";

error

tyrus
type T = Extract<"a" | "b" | "c", "a" | "b">;
const v: T = "c"; 
text
error[E0308]: type mismatch for `v`: expected `"a" | "b"`, found `string`
at /src/main.tyr:2:7
const v: T = "c";
      ^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Conditional types ​

Conditional types choose between two types at compile time. The extends constraint selects the branch, and infer extracts a type from inside the matched structure.

T extends U ? X : Y ​

A conditional type resolves to X when T satisfies the constraint U, and to Y otherwise.

SignatureT extends U ? Then : Else
tyrus
type IsString<T> = T extends string ? boolean : i32;
type FromString = IsString<string>;
const flag: FromString = true;

error

tyrus
type IsString<T> = T extends string ? boolean : i32;
type FromNumber = IsString<i32>;
const count: FromNumber = "zero"; 
text
error[E0308]: type mismatch for `count`: expected `i32`, found `string`
at /src/main.tyr:3:7
const count: FromNumber = "zero";
      ^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

infer R ​

Binds a type variable inside the constraint of a conditional, when the constraint holds, the inferred type becomes the true branch.

SignatureT extends (arg: i32) => infer R ? R : never
tyrus
type Fn = (i32) => string;
type Return<T> = T extends (arg: i32) => infer R ? R : never;
type Result = Return<Fn>;
const value: Result = "hello";

error

tyrus
type Fn = (i32) => string;
type Return<T> = T extends (arg: i32) => infer R ? R : never;
type Result = Return<Fn>;
const n: i32 = 42;
const value: Result = n; 
text
error[E0308]: type mismatch for `value`: expected `string`, found `i32`
at /src/main.tyr:5:7
const value: Result = n;
      ^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Union Types ​

tyrus
type Shape =
    | { kind: "circle"; radius: f64 }
    | { kind: "square"; size: f64 }
    | { kind: "rect"; width: f64; height: f64 };

const printShape = (shape: Shape): void => {
    if (shape.kind === "circle") {
        print(shape.radius); // radius value
    } else if (shape.kind === "square") {
        print(shape.size); // size value
    } else {
        print(shape.width); // width value
        print(shape.height); // height value
    }
};

Tagged unions narrow through literal discriminant checks. The compiler tracks positive and negative branches so each branch exposes the fields available for the narrowed variant set.

Unions also work with enums for type-safe event payloads:

tyrus
enum EventKind {
    Click,
    KeyPress,
    Submit,
}

type Event =
    | { kind: EventKind.Click; x: i32; y: i32 }
    | { kind: EventKind.KeyPress; key: string }
    | { kind: EventKind.Submit; formId: string };

const handleEvent = (event: Event): void => {
    match (event) {
        ({ kind: EventKind.Click, x, y }) => {
            print(`Click at (${x}, ${y})`); // "Click at (10, 20)"
        }
        ({ kind: EventKind.KeyPress, key }) => {
            print(`Key: ${key}`); // "Key: enter"
        }
        ({ kind: EventKind.Submit, formId }) => {
            print(`Submit: ${formId}`); // "Submit: login"
        }
    }
};

Algebraic enums ​

Algebraic enums model a closed set of variants, where each variant may have no payload, positional payload fields, or named payload fields. A match over an algebraic enum must be exhaustive unless it includes _; tuple and struct patterns bind the selected payload directly.

tyrus
enum Command {
    Quit,
    Move(i32, i32),
    ChangeColor { r: u8, g: u8, b: u8 },
}

const main = (): void => {
    const describe = (command: Command): i32 => {
        match (command) {
            Command.Quit => { return 0; }
            Command.Move(x, y) => { return x + y; }
            Command.ChangeColor { r, g, b } => { return (r + g + b) as i32; }
        }
    };

    const result = describe(Command.ChangeColor({ r: 10u8, g: 20u8, b: 30u8 }));

    print(result); // 60
};