Skip to Content
defold-typescript
Get startedGuidesAPILibraries
Core concepts

Script lifecycle helpers

@defold-typescript/types exports identity helpers for Defold script tables. They keep the runtime object unchanged while giving TypeScript a typed self and typed lifecycle hook parameters. self holds per-instance state; for the wider picture — when to reach for a shared module local, a cross-script module singleton, or a VM-global instead — see Where script state lives.

init returns the script's initial state, and that return is the single site TypeScript infers the self type (TSelf) from, so you write the field set once and every other hook's self is typed from it. (When you declare properties, init also receives a self holding just those property values — see Script properties on self — but the return is still the only state-inference site.) No explicit type argument is needed:

import { defineScript } from "@defold-typescript/types";

export default defineScript({
  init: () => ({ speed: 120 }),

  on_input(self, action_id, action) {
    if (action_id == null) {
      // No action_id = raw pointer/mouse-move event; read the cursor off `action`.
      const pointerX = action.x;
      const pointerY = action.y;
      void pointerX; // replace with real usage
      void pointerY; // replace with real usage
      return;
    }

    if (action.pressed) {
      self.speed += action.value ?? 0;
    }

    for (const touch of action.touch ?? []) {
      const finger = touch.id;
      const x = touch.x;
      void finger; // replace with real usage
      void x; // replace with real usage
    }
  },
});

Each source file is exactly one Defold script of one kind: you export a single factory call as default, never two in the same file, and a .script and a .gui_script are always separate files. A script with no init to infer self from takes an explicit type argument instead, in its own file:

import { defineGuiScript, type Hash } from "@defold-typescript/types";

type MenuSelf = {
  root: Hash;
};

export default defineGuiScript<MenuSelf>({
  on_input(_self, action_id, action) {
    if (action_id == null) {
      // No action_id = pointer move; this menu handles only named actions, so bail.
      return;
    }

    if (action.released) {
      const text = action.text;
      void text; // replace with real usage
    }
  },
});

With an explicit type argument (defineGuiScript<MenuSelf>), init's return is checked against MenuSelf rather than inferred from it. That single argument is one of three routes to a typed self, and it is the one that stops working the moment you also declare properties — see Three ways to type self for the other two and for what inference costs you.

The hooks are members of the table defineScript, defineGuiScript and defineRenderScript take, not functions you call. The Defold reference lists them under go and gui, but the engine binds no go.init or gui.update, so neither is declared; to type a standalone handler, use ScriptHooks or InputAction rather than typeof go.on_input.

Note

The samples import Hash for the sake of being copy-pasteable, but the engine value types — Hash, Vector3, Vector4, Quaternion, and the rest — are also declared globally, so a source file that imports nothing can still annotate with them. There is no need to recover one as ReturnType<typeof hash>.

Script properties on self

Declare editor script properties with the value-keyed properties field of defineScript. The key is the property name (written once) and the value is its default, so the value's type flows onto self alongside the state init returns.

Tip

You never call go.property yourself. The transpiler synthesizes the chunk-scope go.property(...) registrations Defold needs from this field — see Why not call go.property yourself for what a direct call costs you.

import { defineScript, type Hash } from "@defold-typescript/types";

export default defineScript({
  properties: {
    adj: vmath.vector3(0, 0, 0), // self.adj: Vector3
    name: hash("initial value"), // self.name: Hash
  },
  init(self) {
    return { velocity: vmath.vector3(0, 0, 0).add(self.adj) };
  },
  update(self) {
    const name: Hash = self.name;
    self.velocity = self.velocity.add(self.adj);
    void name; // replace with real usage
  },
});

Property-backed fields are present on self before init runs, so they need not appear in init's return. The state init returns is still checked on its own — an omitted state field remains a compile error, while omitted property-backed fields are correct.

Defold's build reads each default from the generated Lua text alone. A key may be a name or a literal, and registers under the name JavaScript gives it: ["a-b"] registers a-b and 0x10 registers 16. A default written in a form Defold's build reads is emitted as written:

  • a number, including an infinite one such as 1e400
  • true or false
  • a string without a NUL character
  • hash("...")
  • msg.url() with no argument, one string or three strings
  • vmath.vector3, vmath.vector4 or vmath.quat with no argument, one number or every component as a number
  • a resource marker

A const enum member and a template literal without substitutions compile to one of these forms. Any other default, spread, shorthand member or computed key is computed at build time, and so is a properties value that is not an object literal, such as a const declared elsewhere. The build runs the generated Lua in a sandbox and emits one go.property per property, with the computed value written in a form Defold's build reads. The names are the ones TypeScript types onto self, in JavaScript's key order: each name keeps the position where it first appears, and a later key overrides an earlier value. The order is read from the source, through consts and their spreads, imported ones included, so a function result, a let or an object's field that brings in two or more names fails the build.

import { defineScript } from "@defold-typescript/types";
import { TRAIL_DEFAULTS } from "./trail_defaults";

const BASE = 10;

export default defineScript({
  properties: {
    tint: vmath.vector4(1, 1, 1, 1),
    ...TRAIL_DEFAULTS, // each of its names registers here, in its own order
    width: BASE * 2, // registers `go.property("width", 20)`
    id: hash(`trail_${BASE}`), // registers `hash("trail_10")`
  },
});

A computed default may use Lua's math, string and table libraries, the project's own modules, hash, msg.url, the vmath.vector3, vmath.vector4 and vmath.quat constructors with their operators and components, and vmath.quat_rotation_x, vmath.quat_rotation_y and vmath.quat_rotation_z. A resource marker stays a name: value member. The build fails, with a diagnostic on the script that names the cause, when a default calls an engine runtime API such as go.get_position, uses randomness or reads a file, reads from a library module, runs longer than a second, or computes a value that is not a property type, such as a table or undefined. A method or an accessor fails on that member, and a properties type with an index signature, such as Record<string, number>, fails because its names are not known at compile time.

The sandbox runs Lua 5.4 and turns numbers into strings the way LuaJIT does, so a string built from a number matches what the game computes. Integer arithmetic that passes 2^63 can still differ from LuaJIT, which holds every number as a double.

Only defineScript takes properties. Defold builds go.property only in .script files, so defineGuiScript and defineRenderScript reject the field at compile time and the transpiler refuses to emit it. A GUI or render script that needs a per-object value gets it from a sibling defineScript, which declares the property and sends its value with msg.post in init.

Resource properties

A resource property takes one of seven markers as its default: resource.atlas, resource.buffer, resource.font, resource.material, resource.render_target, resource.texture or resource.tile_source, as in properties: { hero: resource.atlas("/main/hero.atlas") }, which types self.hero as a Hash. Defold's build reads a marker only in a property default, and the engine binds no function by that name. A call or a reference anywhere else, including a module const used as the default, fails the build.

The default itself must be written resource.<kind>("<path>") with a string literal path, or resource.<kind>() with no path. Parentheses, type assertions and a literal key such as ["material"] compile to that form and are accepted. An alias such as const r = resource, an optional call such as resource?.atlas("/a.atlas"), or a key or path held in a variable also fails the build, because Defold's build reads no other form.

Text properties

A string default declares a text property, which the editor shows as a multi-line text field. Defold supports text script properties from 1.13.2:

import { defineScript } from "@defold-typescript/types";

export default defineScript({
  properties: {
    greeting: "Hello!\nWelcome", // self.greeting: string
  },
  init(self) {
    print(self.greeting);
  },
});

When the project targets an older Defold, build and watch refuse the script and write nothing for it, naming the property, its position, and both versions. Any default that may hold a string counts, such as a string | Hash union or a branded string, and the refusal is reported beside every other failure while clean sources are still written:

src/greeter.ts:5:15: script property "greeting" has a string default, which needs Defold 1.13.2 or later; the target is 1.12.4

A direct go.property("greeting", "Hello") also compiles, typed ScriptProperty<string>; it is deprecated like every direct go.property call and meets the same version check.

The same release lets a script read and write a label's text as a component property: go.get<label.Properties>()("#label", "text").

Reading properties in init

Defold applies the declared property values to self before init runs, so init can read them at spawn time. Give init a self parameter and it is typed as the property channel — exactly the declared properties, for reading. This is the natural home for setup that depends on a property, such as playing the initial animation without waiting a frame:

import { defineScript, type Hash } from "@defold-typescript/types";

export default defineScript({
  properties: {
    start_anim: hash("idle"), // self.start_anim: Hash
    max_hp: 100, // self.max_hp: number
  },
  init(self) {
    // `self` here is only the property channel: start_anim and max_hp.
    sprite.play_flipbook("#sprite", self.start_anim);
    return { hp: self.max_hp };
  },
  update(self) {
    // Outside init, `self` is the merged properties + returned state.
    self.hp -= 1;
    void self.max_hp; // replace with real usage
  },
});

Inside init, self is only the property values — reading a field that is neither a declared property nor yet returned is a compile error. The return is still the sole state channel, and every other hook sees the merged properties-plus-state self.

Hovering defineScript, defineGuiScript, or defineRenderScript in the editor now shows the factory's purpose, the hooks each kind accepts (render scripts take only init, update, on_message and on_reload), and a TypeScript example. Hovering an individual callback inside the hook table — init, update, fixed_update, late_update, on_message, on_input, final, on_reload — now shows that hook's Defold description and parameter docs as well. Hovering an action or touch field inside on_input — action.value, action.pressed, touch.tap_count, and the rest — shows that field's Defold description.

At runtime Defold owns self (a userdata-backed table) and a script can populate but not replace it, so the transpiler can't emit a returning init verbatim. It wraps the body in a builder and merges the returned table onto the engine self; a nil/stateless return merges nothing. When init takes a self parameter the builder receives the engine self (so a property read resolves to the real table), and the parameter keeps your name even if it is not literally self. The hooks you write stay in terms of a typed self. A hook parameter must be a plain name, since it takes the engine argument at its position: a destructured, defaulted or rest parameter fails the build, so destructure or default it inside the body.

defineScript and defineGuiScript both type on_input as (self, action_id, action) => boolean | void.

  • action_id is Hash | undefined; Defold uses nil for pointer movement. The == null the examples above test it with is the loose form that narrows both spellings — and undefined, not null, is what you pass back into an engine slot (passing absence).
  • action is InputAction with optional fields such as value, pressed, released, x, y, text, marked_text, and touch.
  • action.touch entries are InputTouch values. The engine sets all twelve fields on every entry, so id, tap_count, pressed, released, x, y, screen_x, screen_y, dx, dy, screen_dx, and screen_dy are never undefined.

defineRenderScript accepts only init, update, on_message, and on_reload, the four hooks Defold calls on a render script. Writing on_input, final, fixed_update, or late_update there is a compile error, since the engine would never run it.

Why not call go.property yourself

Defold registers a script property with a chunk-scope go.property("name", default) call, and that call is what the editor reads to offer the property on a game object. The properties field is that call: the transpiler emits one registration per property, after the module's own local consts and before the hook assignments, with a default that references a module constant computed to the value Defold's build reads.

Writing the call yourself is deprecated, and costs you the typing the field exists for:

  • The property never reaches self. defineScript builds self from properties plus what init returns, and a call in module scope contributes to neither — so self.health is a compile error (TS2339), not merely an untyped read. Recovering it means hand-writing the state type, which puts the property's name and type in a second place that can drift from the registration.
  • The build tells you. build and watch report `go.property` called directly is deprecated; declare the property in `defineScript({ properties })` … on the warning channel, naming the file. It is a warning, not an error: existing code keeps compiling and keeps running.
  • The descriptor route goes with it. A direct call returns a ScriptProperty<T> phantom that ScriptProperties<typeof props> used to unwrap into a self type. Both are deprecated; the properties field replaces the pair.

The migration is mechanical — the name and the default move into the field, and the type follows on its own:

// Before: registers at runtime, but the property is invisible to TypeScript.
go.property("health", 100);

export default defineScript({
  update(self) {
    // @ts-expect-error `health` reaches neither `properties` nor init's return.
    print(self.health);
  },
});
// After: one place for the name and the default, and `self.health` is `number`.
export default defineScript({
  properties: { health: 100 },
  update(self) {
    print(self.health);
  },
});

The emitted Lua is the same either way — go.property("health", 100) at chunk scope — so moving a property into the field changes what the compiler knows, not what the engine runs.

Three ways to type self

Three routes reach a typed self. Which one you pick decides whether TypeScript learns your literal types or widens them away.

RouteSpellingReach for it when
inferred (the default)init: () => ({ … })init exists and the widened return is good enough
annotated initinit(self): State { … }you want the returned state named, with or without properties
both type argumentsdefineScript<Props, State>({ … })there is no init to infer from

Two of those routes name a type, and in both the name belongs to the state channel — what init returns — not to the whole self. Outside init, self is TProps & TInitState: the declared properties merged with the returned state. Neither route describes self on its own, and a state type that happens to repeat the property fields does so because init copied them onto the state, not because it has to.

Naming the state with an annotated init

Annotate init's return type and the state is named with no type argument at all, which is why this route composes with a properties block:

import { defineScript } from "@defold-typescript/types";

type ShipState = {
  phase: "idle" | "boosting";
};

export default defineScript({
  properties: {
    speed: 120,
  },
  init(self): ShipState {
    // Inside init, `self` is the property channel alone.
    void self.speed; // replace with real usage
    return { phase: "idle" };
  },
  update(self) {
    // Outside init, `self` is the merge: `speed` came from `properties`,
    // `phase` from init's return.
    if (self.phase === "boosting") {
      self.speed += 1;
    }
  },
});

Naming both channels with type arguments

A script with no init has no return to infer from, so both channels are spelled as types. defineScript's first type parameter is TProps, the property channel — so whenever properties is declared, pass two arguments, Props then State:

import { defineScript, type Hash } from "@defold-typescript/types";

type ShipProps = {
  speed: number;
};

type ShipState = {
  // Optional because no `init` writes it: the field starts absent.
  phase?: "idle" | "boosting";
};

export default defineScript<ShipProps, ShipState>({
  properties: {
    speed: 120,
  },
  on_message(self, message_id: Hash) {
    // The merge again: `phase` is state, `speed` is property-backed.
    if (message_id === hash("boost") && self.phase !== "boosting") {
      self.phase = "boosting";
      self.speed += 60;
    }
  },
});

A type argument describes the state a script keeps; it does not create it. A field no init assigns is nil on a fresh instance whatever the type says, so model it optional and handle the absent case — here the boost guard asks whether the ship is not already boosting, which is true of a ship that has never boosted.

Why one type argument does not work beside properties

Because TProps comes first, defineScript<ShipSelf> makes ShipSelf the property channel, and the properties block is then checked against that whole shape:

import { defineScript } from "@defold-typescript/types";

type ShipSelf = {
  speed: number;
  phase: "idle" | "boosting";
};

export default defineScript<ShipSelf>({
  properties: {
    speed: 120,
  },
  update(self) {
    self.phase = "boosting";
  },
});

That reports TS2741: Property 'phase' is missing in type '{ speed: number; }' but required in type 'ShipSelf' — the state field is being demanded of the properties block. The fix is the two-argument form above, not a wider properties block. The single-argument form stays correct for a script that declares no properties, which is what the defineGuiScript<MenuSelf> sample at the top of this page is.

What inference costs: literal types widen

Inference widens a string literal to string, so an inferred self keeps the field but loses the union:

import { defineScript } from "@defold-typescript/types";

export default defineScript({
  init: () => ({ phase: "idle" }),
  update(self) {
    // `self.phase` is `string`: the literal widened, so this typo compiles.
    self.phase = "boostng";
  },
});

Either naming route is the opt-out. Annotating the same init pins the union, and the typo becomes a compile error:

import { defineScript } from "@defold-typescript/types";

type ShipState = {
  phase: "idle" | "boosting";
};

export default defineScript({
  init: (): ShipState => ({ phase: "idle" }),
  update(self) {
    // @ts-expect-error `self.phase` is the literal union, so the typo is caught.
    self.phase = "boostng";
  },
});

Widening is the right default for a counter — init() { return { hits: 0 } } then self.hits += 1 needs number, not 0. It is the wrong default for a state machine, and naming the state is how you say so.

Frame-update hooks

Defold calls three per-frame hooks, all sharing the (self, dt) => void shape where dt is the time step in seconds:

HookWhen it runs
updateevery frame
fixed_updateevery fixed physics step (only when fixed time step is enabled)
late_updateevery frame, after update and animation/physics have run
export default defineScript({
  init: () => ({ velocity: 0 }),
  update(self, dt) {
    self.velocity *= 1 - dt;
  },
  late_update(self, dt) {
    void dt; // replace with real usage
  },
});

Receiving messages: on_message

on_message(self, message_id, message, sender) runs when another script or the engine posts to this component. Defold pre-hashes the id, so message_id arrives as a Hash and message as an untyped record. on_message's payload narrowing — the isMessage guard and the onMessage dispatcher that turn that untyped record back into its BuiltinMessages shape — is covered in Typed messages, the same way Where script state lives is the canonical home for self typing.

Hot reload and on_reload

on_reload(self) runs when a component's code is reloaded into a running game — what watch --hot-reload pushes on every successful rebuild, and what the editor's own Reload does.

A reload swaps the code; the state stays. Defold keeps the live self the old code left behind and does not call init again, so anything init established is simply not re-established:

export default defineScript({
  init: () => ({ speed: 120, target: vmath.vector3(0, 0, 0) }),
  on_reload(self) {
    // Reached the running instance with the *old* self; re-apply what init set.
    self.speed = 120;
  },
});

This bites harder in TypeScript than in Lua, because init's return value is the state object: the field set you wrote once in init is exactly what a reload leaves untouched. Add a field to init's return and reload, and the running instance still holds the old shape — the new field is undefined until the game restarts, even though the type says otherwise. on_reload is where you close that gap for the fields worth tweaking live; for the rest, restart the game.

API availability by script kind

Defold scopes two namespaces to a script kind: gui.* resolves only inside a .gui_script, and render.* only inside a .render_script. Every other namespace (msg, vmath, sys, go, …) is available in every kind, with one exception: a render script has no game object, so a function that needs one always raises "no instance could be found" there. The render-script entrypoint leaves those functions out:

The set is read from the engine source of the Defold version the surface is built for. A version whose engine source the package does not vendor keeps every function.

The default @defold-typescript/types entrypoint aggregates all namespaces, so it never rejects a call the engine would allow at runtime — but it also can't catch a gui.* use in a plain .script. To get the engine's wall at compile time, pin the entrypoint matching the file's script kind in that file's tsconfig:

Script kindtypes entrypointNamespaces
.script@defold-typescript/types/scriptuniversal only
.gui_script@defold-typescript/types/gui-scriptuniversal + gui
.render_script@defold-typescript/types/render-scriptuniversal + render, without the functions that need a game object
.editor_script@defold-typescript/types/editor-scripteditor only

.editor_script is not a runtime kind at all — it runs in the editor's Lua VM, so its entrypoint carries editor.* and none of the runtime namespaces. See Editor scripts.

// tsconfig for a .gui_script source tree
{
  "compilerOptions": {
    "types": ["@defold-typescript/types/gui-script"]
  }
}

Under that config gui.* and the universal namespaces type-check while render.* is a compile error. The default @defold-typescript/types keeps every namespace, so the full surface is what you get everywhere until you opt in to a wall.

init, build, and watch never narrow the surface for you: they scaffold and build against whatever entrypoint your tsconfig names — the full @defold-typescript/types by default — and never add, remove, or prune a wall. Narrowing is opt-in, managed by the wall command: it narrows a single-kind source directory to its kind subpath with a standalone tsconfig.json, and wall --check type-checks every wall and the rest of the project. See Wall for the interactive menu, the flag forms, and the one constraint that makes a wall actually hold (import the lifecycle factory from the kind subpath, not the main entry).

On this page