TypeScript Functions

Pick TypeScript in the language menu of the Functions tab to add type annotations to your Functions. Everything in Writing Functions applies: the same export default, the same ctx and args, the same limits.

Anatomy

interface Args {
  itemId: string;
}

export default async function (ctx: any, args: Args) {
  const inventory: string[] = ctx.player.get("inventory") ?? [];
  if (!inventory.includes(args.itemId)) {
    throw new NetStackError("ITEM_NOT_OWNED", "You do not own that item.");
  }
  ctx.player.set("inventory", inventory.filter((id) => id !== args.itemId));
  ctx.room.broadcast("itemUsed", { playerId: ctx.player.id, itemId: args.itemId });
  return { remaining: inventory.length - 1 };
}

How types are handled

Types are erased before your Function runs, so they document your code and help the editor, but they are not checked on the server. Line numbers in errors always match your source.

  • Interfaces, type aliases, generics, as casts, !, optional parameters and satisfies all work.
  • Features that generate code are not supported: enum, namespace and constructor parameter properties (constructor(private x: number)). Use a plain object or const instead of an enum:
const Rarity = { Common: 0, Rare: 1, Epic: 2 } as const;
type Rarity = (typeof Rarity)[keyof typeof Rarity];

export default async function (ctx: any, args: { rarity?: Rarity }) {
  const rarity: Rarity = args.rarity ?? Rarity.Common;
  return { rarity, epic: rarity === Rarity.Epic };
}

Always validate args

Types on args describe what you expect, not what a client actually sends. A cheater can send anything, so still check values at runtime:

export default async function (ctx: any, args: { amount: number }) {
  if (typeof args.amount !== "number" || args.amount < 1 || args.amount > 100) {
    throw new NetStackError("BAD_AMOUNT", "Amount must be between 1 and 100.");
  }
  const gold: number = (ctx.player.get("gold") ?? 0) + args.amount;
  ctx.player.set("gold", gold);
  return { gold };
}

See the Function API for everything on ctx.