Examples

Runnable programs from the examples/showcase/ folder. Compile with lumen compile <file>.ts, or run tests with lumen test.

inventory.ts enums · interfaces · record arrays · for…of · template literals

enum Category { Food, Tool, Book }

interface Item {
  name: string;
  price: int;
  category: Category;
}

function describe(item: Item): string {
  return `${item.name}: $${item.price}`;
}

let items: Item[] = [
  { name: "apple", price: 2, category: Category.Food },
  { name: "hammer", price: 15, category: Category.Tool },
  { name: "novel", price: 9, category: Category.Book },
];

let total = 0;
for (const item of items) {
  console.log(describe(item));
  total += item.price;
}
console.log(`total: $${total}`);

higher-order.ts function values · arrow functions · ternary

function applyTwice(f: (n: int) => int, v: int): int {
  return f(f(v));
}

function triple(x: int): int {
  return x * 3;
}

console.log(applyTwice(triple, 2));               // 18
console.log(applyTwice((x: int) => x + 10, 5));   // 25

let clamp: (n: int) => int = (x: int) => x > 100 ? 100 : x;
console.log(clamp(250));   // 100
console.log(clamp(42));    // 42

config.ts optional fields · ?? · null-narrowing · defer

interface Settings {
  host: string;
  port?: int;
}

function connect(s: Settings): void {
  defer console.log("connection closed");
  let port = s.port ?? 8080;
  console.log(`connecting to ${s.host}:${port}`);
}

function label(name: string | null): string {
  if (name != null) {
    return name;
  }
  return "anonymous";
}

connect({ host: "localhost" });                  // :8080  + closed
connect({ host: "api.example.com", port: 443 }); // :443   + closed
console.log(label("ada"));                        // ada
console.log(label(null));                         // anonymous

math.test.ts test blocks · expect — run with lumen test

function gcd(a: int, b: int): int {
  let x = a;
  let y = b;
  while (y != 0) {
    let t = y;
    y = x % y;
    x = t;
  }
  return x;
}

test "gcd computes greatest common divisor" {
  expect(gcd(12, 8) == 4);
  expect(gcd(17, 5) == 1);
}

ffi-math.ts extern functions · linking libm — lumen compile

// @link m
extern function pow(base: number, exp: number): number;
extern function sqrt(x: number): number;

let hypotSq = pow(3.0, 2.0) + pow(4.0, 2.0);
console.log(sqrt(hypotSq));   // 5
console.log(pow(2.0, 10.0));  // 1024