Skip to Content
defold-typescript
Get startedGuidesAPILibraries
TypeScript

TypeScript gotchas

Sharp edges where TypeScript, the TypeScriptToLua transpiler, or the Defold runtime behave in ways the type system cannot fully express. Each entry names the symptom, explains why it happens, and gives the recommended workaround.

New to TypeScript from Lua? Start with TypeScript vs Lua for the syntax-and-idiom map; this page is the depth catalog you reach for when one of those quirks bites.

Before you start: Lua vs TypeScript gotchas

The one-line version of every trap on this page. Skim it once; jump to the full entry when one bites.

Unary minus on Vector3 / Vector4 silently produces number

Symptom. -v3a compiles cleanly and infers as number, not Vector3. Anything downstream that expects a Vector3 (passing to go.set_position, chaining .add(...), etc.) fails to compile with a confusing error pointing at the use site, not at the -.

declare const v3a: Vector3;

const neg = -v3a; // inferred as `number`, not `Vector3`
const target: Vector3 = -v3a; // TS error here — but the bug is the `-`

Why. TypeScript's TS2362 check ("operand of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum") applies to binary +, -, *, / but not to unary -. The unary form has its own narrow check that does not reject object-typed operands; it just produces number. There is no way to opt a type out of unary negation at the type-system level, so the vector3 interface cannot defend itself.

Typed alternative. Use v.unm() — the same metamethod the Lua runtime would call for -v, but exposed as a typed method:

const neg: Vector3 = v3a.unm(); // returns Vector3

The same gap exists for Vector4; the same workaround applies: v.unm().

How we pin this in the type tests. packages/types/test-d/guide-snippets.ts carries a symmetric proof: one line asserts const _: number = -v3a (which must compile), the next asserts const _: Vector3 = -v3a with @ts-expect-error (which must remain an error). If a future change either fixes the TS behavior or breaks the workaround, exactly one of the two lines flips and the typecheck gate fails.

Enum constants are branded numbers — a bare number won't do

Symptom. A call that the Lua runtime accepts with a magic number fails to typecheck when the parameter is an enum:

go.animate(id, "position.x", 2, 10, go.EASING_LINEAR, 1);  // TS error on `2`
go.animate(id, "position.x", go.PLAYBACK_ONCE_FORWARD, 10, go.EASING_LINEAR, 1);  // ok

Why. Defold's ref-doc encodes an enum member as a bare constant and lists the members' fully-qualified names as a parameter's accepted types. The generated typings recover each constant as a nominally branded number — go.PLAYBACK_ONCE_FORWARD has type number & { readonly __brand: "go.PLAYBACK_ONCE_FORWARD" } — and the parameter's type is the union of those brands. A plain number lacks the brand, so only a real go.PLAYBACK_* (or go.EASING_*) value satisfies it. This is intentional strictness: it stops you from passing the wrong magic number.

Typed alternative. Always pass the named constant (go.PLAYBACK_ONCE_FORWARD, go.EASING_LINEAR, …). The brand is type-only and erases at transpile time to a plain Lua global access, so there is no runtime cost. A branded constant is still assignable to any plain number parameter, so existing numeric signatures keep working.

Naming the enum. Every documented constant union has an exported alias in the namespace it belongs to, so you can spell the type yourself instead of retyping the arms or falling back to number. Where the reference names the enum, the alias carries that name in PascalCase (gui.Easing for the reference's gui.EASING, buffer.ValueType, factory.Status), and it is the same name on every Defold version:

function fadeIn(node: Opaque<"node">, easing: gui.Easing, playback: gui.Playback) {
  gui.animate(node, gui.PROP_COLOR, vmath.vector4(1, 1, 1, 1), easing, 0.5, 0, undefined, playback);
}

A slot that takes only part of a named enum spells that part as Exclude of the enum instead of a second name, so one namespace never carries two names for overlapping sets. gui.get_xanchor returns and gui.set_xanchor takes gui.Anchor minus gui.ANCHOR_TOP and gui.ANCHOR_BOTTOM, while gui.get_yanchor and gui.set_yanchor exclude gui.ANCHOR_LEFT and gui.ANCHOR_RIGHT, so an anchor read from a node passes straight back to its setter. window.get_dim_mode returns window.Dimming, which includes DIMMING_UNKNOWN, while window.set_dim_mode takes Exclude<window.Dimming, typeof window.DIMMING_UNKNOWN>; render.enable_state takes graphics.State minus STATE_ALPHA_TEST_SUPPORTED and STATE_SCISSOR_TEST, which the engine rejects. Write the same Exclude in a wrapper that forwards to such a slot. Signatures and hovers carry the spelling, and the API reference gives each named enum an entry listing its members, with a Lua badge linking the reference's own spelling to its defold.com entry where it differs.

go.Playback includes go.PLAYBACK_NONE. The full union is accepted by go.animate and by the animation playback fields read or written through resource.create_atlas, resource.set_atlas, and resource.get_atlas.

How we pin this in the type tests. packages/types/test-d/guide-snippets.ts asserts the constant is assignable to number (backward compatibility) and to its own brand, while a bare 0 assigned to the brand carries @ts-expect-error. If the brand is dropped or widened, the expected error disappears and the typecheck gate fails. packages/types/test-d/constant-union-aliases.ts does the same for the aliases: representative members are assignable to their alias, and a constant from a sibling group is not. Exhaustive member-set fidelity is held elsewhere: packages/types/test/constant-union-alias-coverage.test.ts catches a brand union left without a name, and packages/types/test/constant-slot-expansion-drift.test.ts checks each documented slot against the reference documentation.

Constants can live in another namespace. The brand is keyed on the constant's fully-qualified name, not on the namespace of the function that accepts it, so an enum can be owned by one namespace and consumed by another. The render buffer-type flags are the worked example: render.get_render_target_width, render.get_render_target_height, and render.enable_texture take a graphics.BUFFER_TYPE_* flag (graphics.BUFFER_TYPE_COLOR0_BIT … _COLOR3_BIT, graphics.BUFFER_TYPE_DEPTH_BIT, graphics.BUFFER_TYPE_STENCIL_BIT), and the named constant lives in the graphics namespace.

render.get_render_target_width(rt, graphics.BUFFER_TYPE_COLOR0_BIT);  // ok
render.get_render_target_width(rt, 0);                                // TS error on `0`

packages/types/test-d/graphics-render-buffer-types.ts pins this: the real graphics constant type-checks and a bare number carries @ts-expect-error.

Comparing a field to a constant does not narrow a union. TypeScript narrows a union on a property only when some arm types that property as a literal, and a branded number is not a literal. bullet3d.shape.get_shape returns one arm per shape, each keyed by its own bullet3d.shape.SHAPE_TYPE_* constant, plus a { type } arm for a triangle mesh. After data.type === bullet3d.shape.SHAPE_TYPE_BOX, data is still that whole union, so passing it to bullet3d.shape.set_shape is a TS error. Check the field the shape carries instead:

const object = bullet3d.get_collision_object("#collisionobject");
if (object !== undefined) {
  const shape = bullet3d.collision_object.get_shape(object, 1);
  const data = bullet3d.shape.get_shape(shape);
  if ("dimensions" in data) {
    data.dimensions = data.dimensions.mul(2);
    bullet3d.shape.set_shape(shape, data);
  }
}

packages/types/test-d/bullet3d-engine-rules.ts pins this: set_shape rejects the unchecked result and accepts it inside the "dimensions" in data check.

A slot the reference types as a bare constant takes the constants its documentation names. Many parameters and getter returns (gui.set_pivot, gui.animate's easing and playback, render.enable_state, window.set_dim_mode, sys.get_connectivity, …) carry no constant list in their ref-doc type, only in their prose — a gui.PIVOT_* list, or "one of the gui.EASING_* constants". The generated typings read that prose, so each such slot is the union of the named constants' brands. A constant from another family, or a generic Opaque<"constant">, is rejected:

gui.set_pivot(node, gui.get_pivot(node));           // OK — getter and setter share the PIVOT_* union
model.play_anim(url, "run", go.PLAYBACK_ONCE_FORWARD); // OK — the family the doc lists
model.play_anim(url, "run", gui.PLAYBACK_ONCE_FORWARD); // TS error — gui's family, not go's
window.set_dim_mode(window.get_dim_mode());          // TS error — the getter can return DIMMING_UNKNOWN

A few slots name no constant at all (gui.new_texture's type lists only strings, iap.get_provider_id, typed once resolve has run for extension-iap, names constants no ref-doc defines) and keep the generic Opaque<"constant">. packages/types/test-d/documented-constant-slots.ts pins the documented calls in each affected namespace.

A table whose keys are constants is a LuaMap, not an object literal. A brand is not one of the three types a TypeScript index signature accepts (string | number | symbol), so a generated declaration cannot describe "a table keyed by these constants" as an index signature — it uses a LuaMap whose key parameter carries the brand, as render.clear's LuaMap<render.ClearBufferKey, number | Vector4> does. Writing one is its own subject: see Lua table constructs. render.render_target is the exception: its reference indexes the table by plain number, so an object literal with computed keys compiles ({ [graphics.BUFFER_TYPE_DEPTH_BIT]: { … } }). Each buffer's fields are checked; the keys are not, so a constant from another family is accepted as a key.

Engine handles are opaque — you cannot fabricate or cast across kinds

Symptom. A GUI node, a render texture or render_target, a buffer, a resource, a box2d b2World/b2Body, and similar engine handles each have a distinct nominal type. A value obtained for one kind is not accepted where another kind is expected, and a plain value (a number, an object literal) is never accepted:

const n = gui.get_node("button");        // Opaque<"node">
render.enable_texture(0, n);             // TS error — a node is not a texture
render.set_render_target(undefined);     // TS error — undefined is not a render_target

Why. Defold's ref-doc names these handles by a bare token (node, texture, buffer, …) with no public structure. The generated typings recover each as Opaque<"<token>"> — a phantom-branded type whose brand is the token string. Distinct tokens carry distinct brands, so they are mutually non-assignable, and because the brand is a unique symbol property no plain value satisfies it. This mirrors the Hash/Url brands: the strictness stops you from passing a handle of the wrong kind or conjuring one from thin air.

Typed alternative. Obtain the handle from the engine API that returns it (gui.get_node, render.render_target, resource.create_buffer, …) and thread that value through. There is no constructor and no meaningful cast across handle kinds — if you find yourself casting, the call you are feeding it almost certainly wants a different handle.

Named handle types. Each handle is also referenceable as a named type alias under its namespace — render.RenderTarget, render.ConstantBuffer, render.Texture, socket.SocketMaster, socket.SocketClient, socket.SocketUnconnected, b2d.B2World, b2d.B2Body — so you can annotate a binding directly (const rt: render.RenderTarget = render.render_target("rt", {})). The alias resolves to the same type the handle-returning function yields — the Opaque<"<token>"> brand, plus the named constants a render.ConstantBuffer takes (constants.tint = vmath.vector4(1, 1, 1, 1)) — so the annotation and the returned value are the same nominal type.

How we pin this in the type tests. packages/types/test-d/ambient.ts passes a documented go.PLAYBACK_* constant to model.play_anim and asserts that both a generic Opaque<"constant"> value and a bare 0 in the same slot carry @ts-expect-error. It also binds render.render_target(...) to a render.RenderTarget-typed variable and asserts a bare 0 cannot be — proving the named alias and the function's return type share one brand. If the brand is dropped or widened to unknown, the expected errors disappear and the typecheck gate fails.

Callback parameters type-check as functions, not unknown

Symptom. Engine APIs that take a callback (timer.delay, http.request, sound.play, factory and particlefx completion callbacks, …) expect a function, and hand it typed arguments. Passing a non-function, or annotating a parameter with a type the slot does not hand over, is a type error:

timer.delay(0.5, false, "tick");                                  // not a function — TS error
timer.delay(0.5, false, (self, handle: string) => {});            // handle is a number — TS error
timer.delay(0.5, false, (self, handle) => timer.cancel(handle));  // OK — handle is inferred as number

Why. Defold's ref-doc names a callback parameter by its whole Lua signature string, e.g. function(self, handle, time_elapsed). The generated typings recover each into a function type with the documented parameter names, and give every parameter the ref-doc describes its documented type: (self: unknown, handle: number, time_elapsed: number) => void. self stays unknown, because the engine passes whatever script instance registered the callback. The return is void: the engine ignores any value a callback returns, and a void return position still accepts a callback that happens to return something.

Typed alternative. Pass the callback inline and leave its parameters unannotated, so each one takes the declared type. A callback declared on its own needs annotations: name the declared type (handle: number, message: sound.PlayCompletion) rather than unknown. Keep self: unknown there and narrow it once at the top (const state = self as { counter: number }). A callback slot the ref-doc describes without parameter types still hands unknown values; narrow those at the point of use, as you would any other unknown. Typings for an older pinned Defold target leave more of these parameters unknown.

Some slots are unknown on purpose — the any wildcard

Symptom. A few API slots are typed unknown: they accept any value going in, and a value coming out cannot be used until you narrow it.

const [first] = socket.skip(1, "a string", 42);  // first is `unknown`
const n: number = first;                          // TS error — narrow it first
const n2 = first as number;                       // OK

Why. Where Defold's own ref-doc types a value as the bare any token — "any Lua value" — the generated typings use unknown rather than guessing a concrete type. socket's utilities (socket.skip) and its option accessors (getoption/setoption) are the cases you will meet. This is deliberate, not a gap: unknown is the honest model for "could be anything." It accepts everything as an argument, and as a result it forces a check before use — unlike TypeScript's any, which would silently switch type-checking off for that value.

Typed alternative. Treat these exactly like callback parameters: narrow or cast at the point of use (first as number), guided by what the Defold API docs say the value is. A branded or nominal type would be wrong here — the whole point of the any token is that no single concrete type fits.

How we pin this in the type tests. packages/types/test-d/socket-any-unknown.ts passes assorted values into socket.skip's wildcard slots (proving any argument is accepted) and asserts a wildcard return is not directly assignable to number via @ts-expect-error, while a narrowing cast is. If a wildcard slot ever widened to any or were mis-mapped to a concrete type, the expected error would flip and the typecheck gate would fail.

if (x) truthiness differs — 0 and "" are truthy in Lua

Symptom. A guard that reads naturally in TypeScript changes meaning after transpile. if (count) in TS is false for 0; the Lua it becomes is true for 0.

function describe(count: number, label: string): string {
  if (count) {            // transpiles to `if count then` — true even when count is 0
    return label;
  }
  return "empty";
}

Why. if (x) transpiles to if x then, a direct pass-through with no coercion. JavaScript and Lua disagree on what counts as falsy: JS treats 0, "", NaN, null, and undefined as falsy; Lua treats only nil and false as falsy. So 0 and "" — falsy in the TypeScript you wrote — are truthy in the Lua that runs. The type system cannot warn you: the code is well-typed in both directions.

Typed alternative. Test the value you actually mean. Use if (count > 0), if (label !== ""), or if (x !== undefined) instead of relying on truthiness. An explicit comparison transpiles to the same comparison in Lua and means the same thing in both languages.

How we pin this in the type tests. packages/transpiler/src/narrowing-transpile.test.ts snapshots transpile(...) of an if (x) guard and asserts the committed Lua is if x then — no coercion inserted. If TypeScriptToLua (TSTL) ever started wrapping the condition in a JS-truthiness helper, the snapshot would change and the gate would fail.

typeof cannot narrow engine values — they are Lua userdata

Symptom. A typeof guard that should match a Defold handle never fires at runtime, even though it type-checks.

function asNode(x: unknown): unknown {
  if (typeof x === "object") {   // transpiles to `type(x) == "table"` — false for a gui.node
    return x;
  }
  return undefined;
}

Why. typeof x === "object" transpiles to type(x) == "table". Defold engine values — gui.node, texture, buffer, b2World, … — are Lua userdata, not tables, so type(handle) returns "userdata" and the branch is skipped. The value form is no better: typeof x transpiles to __TS__TypeOf(x), which returns the string "userdata" for these handles — a value TypeScript's typeof union ("object", "function", "number", …) does not even contain, so you cannot write a matching comparison. typeof x === "number"/"string"/"boolean"/"function" do inline to a reliable type(x) == "…", and those work as written; it is only objects-vs-userdata that breaks.

Typed alternative. Do not reach for typeof to recognise an engine handle. The handles are already nominally typed (Opaque<"node"> and friends — see Engine handles are opaque), so thread the typed value through instead of re-checking it. When you genuinely hold an unknown from a wildcard slot, narrow it with the engine predicate that fits (a nil check, a field probe) rather than typeof.

The one runtime narrowing the engine does support for vmath userdata is the types.is_* family, emitted as user-defined type guards:

declare const v: unknown;
if (types.is_vector3(v)) {
  // v is Vector3 here — v.x is a number, no cast needed
  const x = v.x;
}

types.is_hash, types.is_url, types.is_matrix4, types.is_quat, types.is_vector, types.is_vector3, and types.is_vector4 each narrow their argument to the matching core type. The other is_* / exists names (go.exists, sound.is_music_playing, …) are runtime-state checks on an already-typed value, not type guards, so they stay boolean.

A property read can need the same narrowing even when the engine is consistent. go.get(url, "scale") is typed number | Vector3 because a write may pass a number as a uniform scale, but the engine always reads a Vector3 back. Call go.get_scale() when you want it typed as one.

How we pin this in the type tests. packages/transpiler/src/narrowing-transpile.test.ts snapshots both forms: typeof x === "object" → type(x) == "table", and the value form typeof x → __TS__TypeOf(x). The committed Lua makes the userdata mismatch visible; if either lowering changed, the snapshot would fail.

on_message ids are hashes, not strings

Symptom. A handler that compares message_id against a string literal never fires, even though it reads naturally and (under older typings) compiled. The object it should react to is silently ignored — in the platformer example, the player fell through every wall because the contact handler never ran.

on_message(self, message_id, message) {
  if (message_id == "contact_point_response") {  // never true at runtime
    // ...
  }
}

Why. Defold delivers message_id to on_message as a pre-hashed hash value, not a string — the same way action_id arrives in on_input. Lua's == does no cross-type coercion, so hash_value == "contact_point_response" is always false. The string comparison transpiles verbatim (message_id == "contact_point_response") and silently never matches. ScriptHooks.on_message types message_id as Hash to make the mismatch a compile error rather than a runtime mystery; the string-literal form no longer type-checks.

Typed alternative. Pre-hash the id once at module scope and compare Hash to Hash, exactly as the original Lua does and as on_input already does for action_id:

const msg_contact_point_response = hash("contact_point_response");

on_message(self, message_id, message) {
  if (message_id == msg_contact_point_response) {
    const contact = message as unknown as ContactPoint;  // handler payload is an untyped record
    // ...
  }
}

The handler's message is an untyped Record<string | number, unknown> — cast it to the subset you read. Sender-side payload narrowing by message id lives on msg.post (see the messages guide), not on the handler.

How we pin this in the type tests. packages/types/test-d/lifecycle.ts binds message_id to a Hash inside the handler and asserts a string-literal message_id at the call site carries @ts-expect-error. If on_message ever re-typed the id as a string, the expected error would disappear and the typecheck gate would fail.

window.set_listener hands event and data as separate params

Symptom. A window.set_listener callback reads the resize dimensions off data, but data.width is still number | undefined after checking event == window.WINDOW_EVENT_RESIZED. On a project pinned to Defold 1.13.1 or older it is unknown:

window.set_listener((self, event, data) => {
  if (event == window.WINDOW_EVENT_RESIZED) {
    print(data.width, data.height);  // number | undefined — the check does not narrow data
  }
});

Why. The engine delivers event and data to the callback as two separate parameters, and the WINDOW_EVENT_* constants are branded numbers. TypeScript never correlates two independent parameters, and a branded number is not a unit-type discriminant — so an event == … check cannot auto-narrow data the way a discriminated-union field would. The generated callback types event as the union of the five WINDOW_EVENT_* constants (so you get autocomplete and simple positive event == narrowing) and data as window.EventData, whose width and height are optional because only a resize carries them. On Defold 1.13.1 and older the reference names no payload type, so data is a bare Record<string | number, unknown> there.

Typed alternative. Use the provided isWindowEvent guard — the window mirror of isMessage. It re-introduces the discriminant at the use site and narrows data to that event's payload, so inside a resize check width and height are number:

window.set_listener((self, event, data) => {
  if (isWindowEvent(event, data, window.WINDOW_EVENT_RESIZED)) {
    print("resized:", data.width, data.height);  // data: { width: number; height: number }
  }
});

isWindowEvent is declaration-only: the transpiler lowers the call to a bare event == window.WINDOW_EVENT_RESIZED, so there is no runtime function and no import to add. Only WINDOW_EVENT_RESIZED carries fields; every other event receives an empty table, so data narrows to Record<string, never>. This is the same wall — and the same fix — as on_message ids: the engine hands back a payload whose shape depends on a separate id/event argument, and a declaration-only guard is the path to that exact shape.

Physics listener events narrow with isPhysicsEvent, not a type check

Symptom. A physics.set_event_listener callback checks each event's type, but the event is still the whole union inside the branch, so event.a does not type-check:

physics.set_event_listener((self, events) => {
  for (const event of events) {
    if (event.type == hash("collision_event")) {
      // event is still any of the five events; not all of them have `a`
    }
  }
});

Why. The engine sets type on every event to the hash of its message name, and the generated physics.Event gives each member its own type: Hash<"…">. A Hash is an object type, though, not a literal, so TypeScript cannot use it to pick one member of the union.

Typed alternative. Use the provided isPhysicsEvent guard. It takes the event and its message name and narrows the event to that one member, so a and b carry the fields the engine sets for that event:

physics.set_event_listener((self, events) => {
  for (const event of events) {
    if (isPhysicsEvent(event, "contact_point_event")) {
      print(event.a.mass, event.a.normal);  // a: { position, instance_position, normal, relative_velocity, mass, id, group }
    } else if (isPhysicsEvent(event, "collision_event")) {
      print(event.a.id, event.b.id);  // a: { position, id, group }
    } else if (isPhysicsEvent(event, "trigger_event")) {
      print(event.enter, event.a.group);  // a: { id, group }
    }
  }
});

isPhysicsEvent is declaration-only: the transpiler lowers the call to event.type == hash("contact_point_event"), so there is no runtime function and no import to add. A misspelled name is a compile error. The event union exists from Defold 1.13.2 on; on 1.13.1 and older the reference names no event type, so events is unknown there and the guard does not apply.

null, undefined, and == null all collapse to nil

Symptom. Three TypeScript checks you might think are distinct produce one identical Lua test, so they cannot be told apart at runtime.

function present(x: unknown): boolean {
  if (x === null) return false;       // `x == nil`
  if (x === undefined) return false;  // `x == nil`
  return true;
}

Why. Lua has a single absent value, nil. TypeScript's null, undefined, the strict x === null / x === undefined, and the loose x == null all transpile to x == nil. There is no Lua-level distinction between "explicitly null" and "missing", so a function that tries to treat null and undefined differently cannot — both arrive as nil. There is no ambient nil identifier in TypeScript, so a bare x === nil does not compile: test absence with x === undefined (or the loose x == null, which narrows out both) instead.

Typed alternative. Model absence with a single sentinel. Pick undefined in your TypeScript (it is what the engine's nil maps to most naturally), use x === undefined or x == null to test it, and do not design APIs that depend on distinguishing the two. If you need a third "unset" state, encode it explicitly with a value, not with null-vs-undefined.

The engine functions follow the same sentinel: a nil return the reference documents, or the engine source pushes (factory.create when the spawn fails, tilemap.get_tile for an unknown layer), is typed T | undefined, so narrow it explicitly with !== undefined before use. The guard precisely tests absence and transpiles to ~= nil in Lua — the not-equal counterpart of the == nil that the equal === undefined / === null checks emit — so it does not lean on the divergent TS/Lua truthiness — where 0 and "" are truthy once transpiled — the way a bare if (value) would.

const parent = go.get_parent();   // Hash | undefined
if (parent !== undefined) {
  // parent: Hash — narrowed, safe to use
  go.set_parent(go.get_id("."), parent);
}

How we pin this in the type tests. packages/transpiler/src/narrowing-transpile.test.ts snapshots x === null and x === undefined side by side and asserts both committed lines are x == nil, and pins the !== undefined guard beside them so the committed snapshot shows it lowering to x ~= nil. The collapse and its not-equal counterpart are visible in the snapshot; if TypeScriptToLua (TSTL) ever distinguished the equal checks or emitted the wrong operator for the not-equal one, the gate would fail.

Passing absence: write undefined, never null

Does that mean you can always pass null where an API declares arg?: string | Hash? No — there the expectation is undefined.

The collapse is about absence you test and absence the engine returns. It does not run backwards. An optional parameter is declared T | undefined, and null is not a member of that union, so passing it is a compile error — even though both spellings would have arrived in Lua as the same nil.

arg?: T means omit it or pass undefined. The URL builder is the case the API reference itself documents: leaving the socket out addresses the current game world.

// An absent socket means the current game world.
const door = msg.url(undefined, hash("/door"), "door.ts");

Slots that take a url read the same way — absent means "the thing this script is on".

// An absent camera url means the camera on this game object.
camera.set_fov(undefined, 0.7);
// An absent url means the current game object.
go.set_parent(undefined, go.get_id("rig"));

A later argument forces a placeholder. Lua lets a call stop early; TypeScript has no way to skip a slot in the middle, so reaching a later parameter means spelling undefined for the ones you are not using.

// Skip `position` and `rotation` to reach `properties`.
factory.create("#enemyfactory", undefined, undefined, { health: 100 });
// No options bag, but the callback after it is wanted.
collectionproxy.load("#proxy", undefined, () => {});

Some slots must be passed, even as undefined. A slot declared node: T | undefined, with no ?, takes undefined but cannot be left out. gui.clone_tree and gui.get_tree read nil as the whole scene, while a call with no argument raises in the engine, so the declaration makes you write the undefined.

// Clone every node in the scene; `gui.clone_tree()` raises.
const scene = gui.clone_tree(undefined);

Normalize at the boundary. A T | null that comes from outside the Defold surface — decoded JSON is the realistic source — takes ?? undefined at the point it enters your code, so the null never reaches an engine slot.

// `?? undefined` where the value enters, not a cast at the call site.
const decoded = json.decode('{"socket":null}') as { socket: string | null };
const hero = msg.url(decoded.socket ?? undefined, hash("/hero"), "hero.ts");

The asymmetry is the point, not an aside: x == null stays a blessed way to test absence — it narrows both spellings, which is why this repo keeps that one loose form exempt — while null is never legal to pass.

Why undefined and not null? Lua's nil behaves like undefined, not like null. A missing table key reads as nil, t.x = nil deletes the key, and an omitted argument arrives as nil — all of which mean "not there", undefined's semantics, rather than null's "present but empty". TypeScript also only ever produces undefined on its own, so it is the spelling the language hands you.

How we pin this. packages/transpiler/src/gotchas-argument-sentinel.test.ts reads every ts block above out of this page's own bytes, transpiles it against the shipped declarations, and asserts the omitted argument lowers to Lua nil. It then respells each undefined as null and asserts the compile fails — so a declaration that widened one of these slots to accept null, or narrowed one so undefined stops compiling, reds the gate instead of leaving this passage wrong.

Some optional arguments must be left out, not passed undefined

Symptom. A value typed T | undefined does not compile in some arguments the reference calls optional, such as delay in gui.animate or the options table of go.get, go.set and gui.set, even though leaving the argument out compiles.

Why. The engine checks these arguments whenever a call passes them, so an explicit nil raises at runtime where an omitted one works. TSTL passes undefined as nil, so each such function is declared twice: once without the argument and once requiring a value. On a pre-baked version, which arguments behave this way is read from that version's engine source. A surface generated on the fly from reference docs has no engine source to read, so its generated functions keep the reference's optional arguments and accept undefined; the types do not say whether that version raises. The go.get, go.set, gui.get, gui.set and gui.animate declarations are hand-written and take a value or nothing on every version.

Typed alternative. Branch on the value, and leave the argument out when it is absent:

function fadeIn(delay: number | undefined): void {
  const node = gui.get_node("box");
  const white = vmath.vector4(1, 1, 1, 1);
  if (delay === undefined) {
    gui.animate(node, gui.PROP_COLOR, white, gui.EASING_LINEAR, 0.5);
  } else {
    gui.animate(node, gui.PROP_COLOR, white, gui.EASING_LINEAR, 0.5, delay);
  }
}

How we pin this in the type tests. packages/types/test-d/nil-raising-slots.ts compiles calls to these functions with and without the argument and puts @ts-expect-error on a possibly-undefined value, and the engine binding gate reds when any pre-baked version declares a function taking undefined in an argument whose nil raises.

=== and == compile to the same Lua — strictness is a convention, not a runtime guard

Symptom. Coming from JavaScript you might assume == performs loose equality — coercing its operands before comparing — and reach for === to avoid it. In this toolchain the two operators are indistinguishable in the output, so the coercion === guards against never happens.

function isEmpty(cell: number): boolean {
  const strict = cell === 0;   // → `cell == 0`
  const loose = cell == 0;     // → `cell == 0` (byte-identical)
  return strict || loose;
}

Why. TypeScriptToLua emits Lua == for both operators and never inserts a coercion helper, and Lua == is already non-coercing. The one runtime distinction JavaScript draws between the two — loose equality's coercion, including == null matching both null and undefined — is moot here as well, because null and undefined both collapse to nil (see null, undefined, and == null all collapse to nil). So === buys no runtime safety the == form lacks; strictness is a source convention, not a guard. Contrast if (x) truthiness (see if (x) truthiness differs), which is a real change of meaning crossing into Lua.

Typed alternative. The scaffolded biome.json ships with noDoubleEquals off precisely because the operators are identical in the Lua output, so use whichever reads best — === is no longer enforced for consumers. (Our repo keeps the rule on as house style; its == null exemption also preserves one genuinely useful loose form — x == null narrows out both null and undefined in TypeScript's type-checker, a compile-time distinction even though the emitted Lua is identical.) The real equality footgun is never == versus ===; it is if (cell), which is truthy for 0 once it runs as Lua.

How we pin this in the type tests. packages/transpiler/src/narrowing-transpile.test.ts transpiles cell === 0 and cell == 0 in one snippet and asserts both lower to the same cell == 0 — the loose form gets no coercion helper. If TypeScriptToLua (TSTL) ever started coercing ==, the two lines would diverge and the gate would fail.

as is a compile-time assertion, not a runtime check

Symptom. A cast that compiles cleanly does nothing at runtime — the value is never validated, and a wrong assertion produces a silent type mismatch later, not an error at the cast.

function first(values: unknown): number {
  const n = values as number;   // transpiles to `local n = values` — no check
  return n + 1;                 // runs even if `values` was a string or a table
}

Why. const n = first as number transpiles to local n = first: the cast is erased entirely. TypeScript's as is a compile-time assertion that you, the author, know the type — it inserts no runtime guard. So a cast that is wrong does not throw at the cast site; the bad value flows on until some Lua operation on it misbehaves, far from the cause. This is the same erasure that makes branded constants and opaque handles zero-cost — useful there, a footgun when you use as to "convert" an unknown.

Typed alternative. When you actually need to check a value (a wildcard unknown, untrusted input), narrow it with a real runtime test — typeof x === "number" (reliable for primitives, see the typeof entry above), a === nil check, or a field probe — before using it. Reserve as for the cases where you already know the type from context the type system can't see, exactly as with callback and wildcard params.

How we pin this in the type tests. packages/transpiler/src/narrowing-transpile.test.ts snapshots const n = x as number and asserts the committed Lua is local n = x with no inserted check. If a cast ever started emitting a guard, the snapshot would change and the gate would fail.

Component properties are catalogued per namespace

Symptom. Defold component properties — the values you address at runtime through go.get/go.set/go.animate with a string id ("color", "position", "size", …) — do not appear as members on the namespace object. There is no label.color you can read directly.

Why. These properties are not module-level globals; they are per-component fields keyed by a string id passed to go.get(url, "color"). The ref-doc lists them as PROPERTY elements with a name and a type but no addressable symbol. The generated typings recover each namespace's properties into an in-namespace interface Properties { … } so the name and type survive as a committed, drift-gated catalog. For example, label.Properties carries color: Vector4, size: Vector3, scale: Vector3, and so on.

Typed alternative. Read a property's type off the catalog with an indexed access — label.Properties["color"] is Vector4. The catalog also makes go.get, go.set and go.animate type-aware: a literal key drawn from go's own transform properties narrows the result and the written value to the property's real type. go.get(url, "position") is Vector3, go.get(url, "scale") is number | Vector3, and go.set(url, "euler", v3) type-checks while go.set(url, "position", "oops") and go.set(url, "position", vmath.quat()) are rejected: a known transform key takes only its own value type. The single-component keys narrow too: go.get(url, "position.x") is number, as is every .x, .y, .z and .w key of position, rotation, euler and scale, while go.get(url, "scale.xy") is a Vector3 whose z is always 1. go.set(url, "scale.xy", 2) also type-checks, because the engine applies a number to both x and y. go.animate types its target value per key the way the engine converts it: a number fills every component of a vector, so go.animate(url, "position", go.PLAYBACK_ONCE_FORWARD, 100, go.EASING_LINEAR, 1) moves to (100, 100, 100), while "rotation" takes only a quaternion. Any other key — a Hash, a dynamic string, or a fragment-addressed cross-component property like go.get("#sprite", "tint") — takes or returns the documented wide union, so hashed and runtime access keep working unchanged.

A scene address names the component for you. After scene-types runs, a literal address your scenes declare carries its component's kind or script, and the bare call reads that catalog: go.get("/logic#sprite", "playback_rate") is number, go.get("/enemy#controller", "speed") is the type the script declares, and a key the script does not declare is a type error. A literal with no #, such as ".", is a game object, so it takes only the transform keys. go.cancel_animations reads the same catalog and takes only the keys it can animate: go.cancel_animations(".", "positon") and a script property holding a Hash are type errors, because the engine raises on both. Every other address — "#", a runtime string, a Url, a Hash, or a literal the scenes do not declare — takes the transform keys at their types and any other key at the wide union.

Name the component to narrow a cross-component property. A string url the scenes do not declare, like a "#sprite" composed at runtime, cannot tell the type system which component it targets. When you know the component, name it with a type argument and the result narrows to that component's catalog:

const animation = go.get<sprite.Properties>()("#sprite", "animation"); // Hash, not the wide union
go.set<sprite.Properties>()("#sprite", "playback_rate", 2);            // value gated to number
go.get<sprite.Properties>()("#sprite", "nope");                       // type error — not a sprite property
go.set<sprite.Properties>()("#sprite", "animation", hash("run"));     // type error — animation is read-only
go.animate<sprite.Properties>()("#sprite", "scale", go.PLAYBACK_ONCE_FORWARD, 2, go.EASING_LINEAR, 1); // a number fills the vector3
go.animate<sprite.Properties>()("#sprite", "image", go.PLAYBACK_ONCE_FORWARD, 2, go.EASING_LINEAR, 1); // type error — a Hash cannot be animated

The form is curried — go.get<P>()(url, property) — on purpose. TypeScript has no partial type-argument inference: if P and the property key were both type parameters on one call, supplying <sprite.Properties> would force the key to its default and collapse the return to the component's whole value union. The empty () fixes P, then the inner call infers the key from the "animation" argument, recovering the exact field type. The transpiler drops the empty call, so Lua receives go.get("#sprite", "animation"). A property the engine refuses to write is readonly in its catalog, and neither go.set<P>() nor go.animate<P>() accepts its key; go.animate<P>() also accepts only keys whose value is a number, vector3, vector4 or quaternion, the kinds the engine can animate. That covers every property the reference marks READ ONLY, plus the ones the engine source reads but never writes: model "animation", sprite "texture0" and a factory's "prototype". You are naming the component yourself — nothing checks that "#sprite" actually resolves to a sprite — so this is a typed convenience over an unverified url, not a correctness guarantee. The bare direct call (go.get("#go", "position")) is unchanged for the transform default, and a fully dynamic key still falls through to the wide union. The catalogs also declare the keys the engine handles that the reference leaves out. model.Properties accepts "texture0" through "texture15" in place of upstream's textureN placeholder on every pre-baked Defold version, plus "material" and "skin"; a surface generated from a reference doc alone keeps the reference's "texture0" through "texture7". sprite.Properties adds "texture0". Label and sprite vector properties take one number key per component, .x through .z on a Vector3 and .x through .w on a Vector4, plus a Vector3 .xy key on a Vector3, so go.get<label.Properties>()("#label", "color.w") is number. physics.Properties adds "bullet", a boolean that only Box2D supports. factory.Properties and collectionfactory.Properties declare "prototype". A mesh.Properties catalog declares "vertices", "material" and "texture0" through "texture15". Every resource key is a Hash.

Name the script to read or tune another object's declared properties. The same generic also types the cross-script channel — reading or writing a property a different script declared, addressed by its script-component url (go.get("/enemy#controller", "speed")). This is distinct from a component property and from the self-side access inside the owning script: it is how one object tunes another object's declared state. A script declares its editor properties with the value-keyed properties field of defineScript, and exports that shape as a nameable type with ScriptPropertiesOf<typeof script>; another script names it as the P generic to get a typed read and a value-gated write:

// enemy.ts — the owning script declares its properties
export default defineScript({
  properties: { speed: 100, target: vmath.vector3() },
});
export type EnemyProps = ScriptPropertiesOf<typeof import("./enemy").default>;

// elsewhere — another object reads and tunes them by url
const speed = go.get<EnemyProps>()("/enemy#controller", "speed");  // number
go.set<EnemyProps>()("/enemy#controller", "speed", 250);           // value gated to number
go.get<EnemyProps>()("/enemy#controller", "missing");              // type error — not declared

ScriptPropertiesOf extracts the same TProps the owning script's self carries, so the cross-script type and the owning script's self stay one source of truth — there is no second hand-maintained interface to drift. As with the component generic, you name the script yourself; nothing verifies the url resolves to that script. When the url is a literal your scenes declare, the bare go.get("/enemy#controller", "speed") reads the same shape off the scene types with no generic.

Check the properties a factory spawns with. The fourth argument of factory.create seeds the spawned script's declared properties. The bare form takes an object literal with any names, or a LuaMap keyed by string whose values are property types (number, boolean, string, Hash, Url, Vector3, Vector4, Quaternion): the engine skips a hash key, and one value of any other type drops every property. Name the spawned script's shape in the curried form and the table is checked against it: any subset of the declared properties is accepted, and an undeclared name or a wrongly typed value is a type error:

// spawn an enemy with its own speed
const id = factory.create<EnemyProps>()("#enemyfactory", undefined, undefined, { speed: 250 });
factory.create<EnemyProps>()("#enemyfactory", undefined, undefined, { sped: 250 }); // type error — not declared

The form is curried for the same reason as go.get<P>(): the empty call names the shape, and the build removes it, so the engine receives factory.create("#enemyfactory", ...). You name the script yourself; nothing verifies that the factory's prototype runs it.

Check the properties a collection factory spawns with. collectionfactory.create seeds each spawned instance's script properties from a table keyed by instance id, and the engine raises on an id that is a string rather than a hash, so the bare form takes only a map keyed by hash("/enemy_leader"), and each instance's table follows the factory.create rule above. The curried form maps each instance id, as the collection addresses it, to that instance's script shape and checks every instance's table against it; an unknown id is a type error too:

type SquadProps = { "/enemy_leader": EnemyProps; "/enemy_1": EnemyProps; "/medic": MedicProps };
const ids = collectionfactory.create<SquadProps>()("#squadfactory", undefined, undefined, {
  "/enemy_leader": { speed: 250 },
  "/medic": { heal: 9 },
});
collectionfactory.create<SquadProps>()("#squadfactory", undefined, undefined, {
  "/nobody": { speed: 1 }, // type error — not an instance of the collection
});

The build removes the empty call and hashes each id, so the engine receives {[hash("/enemy_leader")] = {speed = 250}, ...}. It can hash only the ids it sees at the call, so two rules follow: call collectionfactory.create<P>() directly rather than storing it, and pass properties as an object literal. The build reports anything else as an error. As with factory.create<P>(), nothing verifies which script each instance runs.

How we pin this in the type tests. packages/types/test-d/guide-snippets.ts asserts label.Properties["color"] is assignable to Vector4 and that a string annotation on the same member carries @ts-expect-error. packages/types/test-d/go-property-accessors.ts pins the typed go.get/go.set: narrow keys resolve to Vector3/Quaternion/number | Vector3, a wrong-typed go.set value on a transform key and a wrong-typed go.get assignment carry @ts-expect-error, a number written to "scale.xy" type-checks, and the Hash/dynamic-string fallback still type-checks. packages/types/test-d/go-animate-property-values.ts pins go.animate: a number fills a vector key, a quaternion into "position" or a number into "rotation" carries @ts-expect-error, a dynamic or hashed key keeps the wide target, the curried form rejects read-only and non-numeric keys of sprite.Properties and of a ScriptPropertiesOf shape, and go.cancel_animations(".", "positon") carries @ts-expect-error. packages/types/test-d/go-property-access.ts pins the caller-named-component generic: go.get<sprite.Properties>()("#sprite", "animation") is Hash, a wrong key, a wrong value type and a write to the read-only "animation" carry @ts-expect-error, and the bare transform call still resolves; it also pins the cross-script channel — a ScriptPropertiesOf<typeof enemyScript>-named read is typed, a write is value-gated, and a wrong key or wrong value type carries @ts-expect-error. packages/types/test-d/factory-spawn-properties.ts pins the spawn form: a partial, empty or omitted table compiles and the result is Hash | undefined, an undeclared key, a wrong value type and a Hash for a Vector3 property carry @ts-expect-error on the inline call and on a stored applier, and the bare factory.create still takes any table. packages/types/test-d/collectionfactory-spawn-properties.ts pins the collection form: a partial, empty or omitted table compiles and returns the same id table as the bare form, while an unknown instance id, an undeclared key, a wrong value type and a Hash for a Vector3 property carry @ts-expect-error. packages/types/test-d/component-properties.ts pins the member types the catalogs resolve to: the camera members read as number, camera.projection / camera.view as Matrix4 and sprite.frame_count as number, with a Hash annotation on the last carrying @ts-expect-error; every model texture key "texture0" through "texture15" reads and writes as Hash, sprite "texture0" and mesh "vertices" read as Hash, and the "textureN" placeholder, the out-of-range "texture16" and an undeclared mesh key carry @ts-expect-error. The same file pins the keys taken from the engine source at their kinds, including the "position.x"-style transform keys, and puts @ts-expect-error on a typed write to model "animation", sprite "texture0" and each factory's "prototype". packages/types/test-d/scene-address-properties.ts pins the address-resolved form: a linked script's keys and their vector elements read at their declared types while an undeclared key, a transform key and a string key carry @ts-expect-error, as do a Hash property and an undeclared key passed to go.cancel_animations; a "sprite" or "collisionobject" address types its catalog's keys and still accepts a material constant; and "", "#", an unregistered kind, a Url, a Hash and a string keep the transform-plus-wide typing, while a literal with no # rejects a non-transform key. packages/types/test-d/lifecycle.ts proves ScriptPropertiesOf extracts exactly the declared property shape (excess and wrong-typed fields carry @ts-expect-error), tying it to the self channel. If the property catalog is dropped, its member types change, or the overloads regress, one of these lines flips and the typecheck gate fails.

GUI node properties are a closed set

Symptom. gui.get(node, "positon"), gui.set(node, "colour", v) and gui.cancel_animations(node, "positon") are type errors. So is gui.set(node, "tint", v) for a material constant, gui.animate(node, "rotation", vmath.vector3(0, 0, 45), gui.EASING_LINEAR, 1), and any gui.get, gui.set, gui.animate or gui.cancel_animations call whose property name is a string variable.

Why. The engine looks a name up in a fixed table of node properties: position, rotation, euler, scale, color, outline, shadow, size and slice9, each with .x to .w sub-keys, plus the scalars inner_radius, fill_angle, leading and tracking. gui.animate and gui.cancel_animations raise for any other name. gui.get and gui.set try a material constant next, and raise if the node's material has none by that name. A string name must be one of the node properties, so a typo fails when you compile rather than when the script runs.

Typed alternative. Each name reads and writes its own type. A vector property reads as a Vector4 and takes a Vector4 or a Vector3. rotation reads as a Quaternion and takes only a Quaternion; set euler to work in degrees. A sub-key or a scalar is a number. gui.animate takes its target the way the engine reads it: rotation takes only a Quaternion, a sub-key or a scalar a number, and any other vector a Vector4, a Vector3 or a number, which fills every component. gui.cancel_animations takes the names gui.animate takes, or none to cancel every animation on the node. A gui.PROP_* constant works wherever its name does. Name a material constant, or a name you only know at run time, with hash(...): that form takes an options table and returns the union of values a constant can hold. The table takes one of index, key or keys, because the engine raises when it gets more than one. A material constant cannot be animated.

const node = gui.get_node("box");
const position = gui.get(node, "position"); // Vector4, no cast
gui.set(node, "position.x", position.x + 10);
gui.set(node, "rotation", vmath.quat_rotation_z(math.rad(45)));
gui.animate(node, gui.PROP_COLOR, vmath.vector4(1, 1, 1, 0), gui.EASING_LINEAR, 0.5);
gui.set(node, hash("tint"), vmath.vector4(1, 0, 0, 1));
gui.set(node, hash("tint_array"), vmath.vector4(0, 1, 0, 1), { index: 2 });

The gui component's own resources. gui.set(msg.url(), property, value, options) addresses the gui component instead of a node. It takes "material", "materials", "fonts" or "textures" with a resource hash; the last three name their entry with the key option. A property a native extension registers is named with hash(...). Only "textures" accepts undefined as the value, which removes the runtime texture mapping key names. Engines before Defold 1.13.1 reject that nil, so on a project pinned to Defold 1.13.0 or older the removal form is a type error.

How we pin this in the type tests. packages/types/test-d/gui-property-values.ts pins each read type ("position" is Vector4, "rotation" is Quaternion, a sub-key or each of the four scalars is number, and a gui.PROP_* constant reads as its name) and puts @ts-expect-error on a misspelled name, a material-constant string passed to gui.animate, a sub-key or a vector on each scalar, a vector written to rotation, a vector written to a sub-key, a vector3 or a number animated into rotation, a vector animated into a sub-key or a scalar, a misspelled name passed to gui.cancel_animations, an options table holding two of index, key and keys, undefined for "fonts" and a node property on the msg.url() form. It also compiles the hash(...) forms and the "textures" removal. packages/types/test/versions.test.ts compiles the removal against every committed surface whose vendored engine has the nil branch, and rejects it on the rest. packages/types/test-d/kinds/gui-script-proof.ts proves the typed read reaches a gui script.

Field-documented tables are typed object shapes, not opaque records

Symptom. A table param or return whose Defold ref-doc spells out its fields, or whose official example proves a stable shape, is no longer the opaque Record<string | number, unknown> it once was. sys.get_sys_info() returns a concrete object — system_name, gmt_offset, and the rest are typed members you can read directly and that auto-complete; a misspelled field is a compile error, not silent unknown.

const info = sys.get_sys_info();
const name: string = info.system_name;   // typed string, no cast
const offset: number = info.gmt_offset;  // typed number
// @ts-expect-error not_a_field is not a field of the sys info table
info.not_a_field;

Why. Many Defold table slots carry their field structure only in the doc HTML, in one of four regular shapes: a <dt><code>field</code></dt><dd><span class="type">T</span></dd> definition list, a <ul> whose items read <span class="type">T</span> <code>field</code> (type before name), a dash-list option bag whose items read field <span class="type">T</span> / <code>field</code> <span class="type">T</span> (name before type), or a code-dash field that reads <code>field</code> - <span class="type">T</span> (name in <code>, then dash, then type — sys.open_url's target attribute). The generator parses these shapes and emits an inline object type instead of the Record fallback, so the field names and types survive. Two nested shapes are also recovered: a <dl> declaring a single table-typed field whose keys sit in an immediately-following <ul> typed-field list (window.get_safe_area() now returns { safe_area: { x: number; y: number; … } }), and a flattened <ul><li><dl> option bag whose table entries are followed by their member fields (resource.create_atlas groups animations and geometries into nested objects). A recovered table field whose <dd> prose reads "a list of …" emits an array of that recovered element shape rather than a single object (resource.get_atlas's animations and geometries become { … }[]); the [] is appended only when member fields were recovered. The atlas tables resource.create_atlas and resource.set_atlas take are stricter: their animations and geometries are non-empty lists ([{ … }, ...{ … }[]]) rather than { … }[], because the engine rejects an atlas with no geometry or no animation, and each animation takes either a non-empty frames list or both frame_start and frame_end. A "list" field with no recovered member shape but a machine-readable numeric element type — its <dd> reads "a list of … in the form {px0, py0, …}" / "{i0, i1, …}", a flat comma-separated list of numeric placeholders — emits number[] (resource.create_atlas/set_atlas's vertices/uvs/indices); a brace form with quotes, nested braces, or non-numeric identifiers is never guessed and stays Record. A "list" field with neither members nor a numeric brace form (opaque maps, the wholesale geometries Record) stays Record. A cross-reference form is also recovered: a table slot with no inline field list of its own whose doc carries a See <a href="…#<element>"> pointer to a sibling element in the same module adopts that element's already-recovered fields, unless a curation supplies that slot's shape directly. Resolution is one hop only. A supplementary See pointer sitting beside an untyped name-only <ul> field list (<li>field</li> items with no <span class="type">) is also recovered: the slot adopts the referenced element's fields filtered to the names the own <ul> enumerates (resource.get_atlas lists texture/geometries/animations then points at resource.set_atlas, so it adopts those three only — the sibling's unlisted vertices/uvs/indices are excluded). A See pointer beside an element's own typed field list still loses to the direct parse, which already recovers those fields. Tables with no recoverable shape (the wholesale geometries Record, opaque key→value maps) keep the Record type — there is no single machine-readable structure to recover. Two deliberate distinctions: a recovered input parameter's fields are optional (an option bag accepts a partial or empty {}, exactly as the old Record did), while a return table's fields are required (the engine always populates them); and recovery nests at most one level — a deeper table field with no recovered keys stays Record. A variant return — one whose members depend on a discriminant, as physics.get_shape's do on its type field — is the exception to the required rule: it is hand-curated as a single record whose kind-specific fields are optional, because only one kind's fields are present in any given value. physics.set_shape takes a separate union discriminated on type — a sphere with diameter, a box with dimensions, a capsule with diameter and height — so a table get_shape returns is rebuilt into its kind's arm before it is passed back.

Typed alternative. Read the members directly — sys.get_sys_info().system_name, liveupdate.get_mounts()[0].uri, tilemap.get_tile_info(url, layer, x, y)?.index — instead of indexing an opaque record and casting. For an options argument, pass only the fields you need (image.load(data, { flip_vertically: true })); omitted fields and {} still type-check, except the fields the engine reads unconditionally, such as the type, format, width and height of a resource.create_texture table, which stay required. To build the table render.render_target takes ahead of the call, type it as render.RenderTargetParams, which every pin declares: on 1.13.2 and newer it is the reference's own struct (one render.RenderTargetBufferParams with a required format, width and height per buffer key, plus an optional sample_count, and from 1.14.0 an optional type), and on older pins it is PlainTable, which takes any table.

How we pin this in the type tests. packages/types/test-d/sys-info-table-fields.ts asserts sys.get_sys_info().system_name is assignable to string and that a bogus field carries @ts-expect-error; packages/types/test-d/example-shaped-table-curations.ts pins the example-proven liveupdate.get_mounts() and tilemap.get_tile_info() shapes; packages/types/test-d/physics-set-shape-fields.ts pins the variant physics.get_shape() record — type reads as number, while diameter and height need narrowing before they are; packages/types/test-d/resource-atlas-frame-forms.ts pins the atlas tables — empty lists, an animation with neither frame form, and an ordinary T[] carry @ts-expect-error; packages/types/test-d/b2d-backend-shape-kinds.ts pins each Box2D backend's shape kinds — a v2 fixture rejects a capsule and a v3 shape rejects a chain. The fidelity audit and the emitter share the table recovery and curation data (packages/types/src/emit-dts.ts), so the recordTables loss gate and the emitted surface cannot drift; if a recovered field's type regressed to unknown the audit's unknownTokens would surface it.

Texture format constants can be undefined

Symptom. On Defold 1.13.2 and newer targets, a render.render_target or resource.create_texture table that names a format constant directly fails to typecheck:

render.render_target({
  [graphics.BUFFER_TYPE_COLOR0_BIT]: {
    format: graphics.TEXTURE_FORMAT_RGBA, // TS error: the constant may be `undefined`
    width: 1024,
    height: 1024,
  },
});

Why. The engine registers a texture format constant only when the graphics driver supports that format, so on a device without it the Lua global is nil. The typings declare every graphics.TEXTURE_FORMAT_* constant as possibly undefined, except graphics.TEXTURE_FORMAT_DEPTH and graphics.TEXTURE_FORMAT_STENCIL, which always exist. A buffer's or texture's format takes a graphics.TextureFormat, which excludes undefined, so an unguarded constant is rejected. Pins older than 1.13.2 declare every format unconditionally, and their render.render_target takes an open record.

Typed alternative. Read the format constant into a local, check it, and pass the narrowed value:

// the engine registers a texture format only when the driver supports it
const format = graphics.TEXTURE_FORMAT_RGBA;
if (format !== undefined) {
  const target = render.render_target({
    [graphics.BUFFER_TYPE_COLOR0_BIT]: { format, width: 1024, height: 1024 },
  });
}

The check runs at runtime too, so a device without the format takes your fallback instead of handing the engine a nil format. When a render script's init builds the target, return undefined from init if the format is missing, and open each other callback that reads self with if (self === undefined) return;. A depth or stencil buffer needs no check.

How we pin this in the type tests. packages/types/test-d/engine-arity-overloads.ts passes a depth-only table and a checked RGBA table to both render.render_target arities, and puts @ts-expect-error on an unguarded format, a buffer with no width, a wrap mode given a filter constant, and an open record.

Box2D v3 query hits need the "v3" type argument

Symptom. In a project built with the Box2D v3 backend, a b2d.world.cast_ray hit type-checks as a v2 fixture hit. hit.fixture.index compiles and fails at runtime, while hit.shape.shape_id is rejected:

const [hits] = b2d.world.cast_ray(world, origin, translation);
for (const hit of hits) {
  hit.shape.shape_id; // TS error: a v2 hit's shape is a fixture table
}

Why. The typings declare both Box2D backends at once, and a call cannot tell which one the project builds with. b2d.world.cast_ray, b2d.world.cast_ray_closest, b2d.world.cast_shape, b2d.world.overlap_aabb and b2d.world.overlap_shape take the same arguments on both backends but return different tables. A v2 hit sets fixture and shape to one fixture table; a v3 hit has no fixture, and its shape is a shape table with a shape_id. The overlaps return fixture tables on v2 and shape tables on v3. A call with no type argument returns the v2 tables.

Typed alternative. Pass <"v3"> to pick the v3 form of each of the five queries:

// a project built with the Box2D v3 backend
const world = b2d.get_world();
if (world !== undefined) {
  const origin = vmath.vector3(0, 0, 0);
  const translation = vmath.vector3(100, 0, 0);
  const [hits] = b2d.world.cast_ray<"v3">(world, origin, translation);
  for (const hit of hits) {
    print(hit.shape.shape_id, hit.point, hit.fraction);
  }
}

The type argument exists on Defold 1.13.2 and later targets, and <"v2"> names the default. It changes only the types: the Lua is the same call.

How we pin this in the type tests. packages/types/test-d/b2d-backend-query-hits.ts reads the v3 fields through <"v3"> on all five queries and puts @ts-expect-error on fixture. It reads the v2 fields with no type argument and with <"v2">, puts @ts-expect-error on shape_id, and rejects <"v4">. packages/types/test/overload-reachability.test.ts fails when any generated declaration has two forms that take the same arguments, since a call could never reach the second.

async/await work but there is no event loop

Symptom. You can write async functions, await, and Promise (the Promise type ships in the ES2022 lib), and it type-checks and transpiles. What does not exist is a JavaScript event loop: there is no setTimeout, no I/O microtask queue, and no scheduler that drains pending promises between frames. A promise advances only when something resolves it synchronously on the current call stack.

async function rollLater(): Promise<number> {
  return 42; // resolves synchronously
}

export async function main(): Promise<void> {
  const r = await rollLater(); // runs to completion in the same call
  print(r);
}

Why. TypeScriptToLua implements async/await itself, on top of Lua coroutines:

  • An async function is lowered to __TS__AsyncAwaiter(generator), which returns a __TS__Promise and runs the function body inside a Lua coroutine.
  • await x is lowered to __TS__Await(x), which yields the value through the body's Lua coroutine. The awaiter wraps the yielded value as Promise.resolve(x), registers a continuation, and coroutine.resumes the body with the result once that promise settles.
  • __TS__Promise is TSTL's own Lua class with then/catch/finally/all/resolve/reject. Resolution is callback-based and synchronous: a callback registered on an already-settled promise fires immediately; otherwise it is stored until resolve()/reject() is called.

These helpers ship in lualib_bundle.lua, which the build writes to its runtime folder; the emitted module requires it by the path it lands at, require("lib.defold_typescript.lualib_bundle") by default. No setup or polyfill is needed.

The consequences are where it bites:

  • Awaiting an already-resolved or synchronously-resolving promise runs to completion in the same frame — fine, and reads well.
  • There is no timer or I/O integration. await new Promise((r) => setTimeout(r, 1000)) cannot be written with a global setTimeout — there is none, so a bare call is a compile error (TS2304, Cannot find name 'setTimeout'), not a silent runtime failure. Import one from @defold-typescript/types/timers instead (see Importable polyfills below). A promise that nobody resolves leaves the async function suspended forever, with no error and no warning.
  • A rejected promise with no .catch is silently dropped; there is no Node-style "unhandled rejection" report.

The engine scheduler bridge. What the JS runtime lacks — a thing that advances pending work between frames — Defold supplies as timer.delay: a frame-driven scheduler that fires a callback on a later frame. That callback is the hook. Resolve a Promise from inside a timer.delay callback and the await waiting on it resumes when the engine fires the timer, not before. Bridge it by hand by stashing the promise's resolve and calling it from the callback:

function waitSeconds(seconds: number): Promise<void> {
  return new Promise<void>((resolve) => {
    timer.delay(seconds, false, () => resolve()); // engine callback drives the promise
  });
}

Importable polyfills. You do not have to hand-roll that bridge. The first timer-polyfills slice ships it as named module exports:

import { setTimeout, setInterval, clearTimeout, clearInterval, wait } from "@defold-typescript/types/timers";

setTimeout/setInterval take milliseconds (the web-familiar unit) and return a numeric timer handle; pass that handle to clearTimeout/clearInterval — or to Defold's own timer.cancel, which is the same handle. wait takes Defold-native seconds and returns a Promise<void> you can await:

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

export async function main(): Promise<void> {
  await wait(1); // resumes when the engine timer fires, not before
  print("one second later");
}

These are not ambient globals: each script is an isolated Lua chunk with no shared scope, so the import lowers to a require of the timer runtime the build writes to its runtime folder. That runtime requires lualib_bundle in turn, so a timers import brings both files with it. Because there is no global, a bare setTimeout(...)/setInterval(...) (the muscle-memory web form) is a compile error — TS2304: Cannot find name 'setTimeout' — under the scaffolded lib: ["ES2022"] surface (no DOM/Node globals). That error is the warning: add the import { setTimeout, … } from "@defold-typescript/types/timers" line and it resolves. Your editor does this for you — tsserver lists the timers module in autocomplete and offers an Add import from "@defold-typescript/types/timers" quick-fix on the TS2304 squiggle, so the fix is one keystroke (works in any tsserver-backed editor; no extension needed). Do not "fix" it by widening lib to "DOM" or adding @types/node — that would restore a global setTimeout declaration that type-checks but has no runtime behind it in Defold, turning the honest compile error into a silent forever-suspended await.

Caveats. The polyfills are timer-backed, not a drop-in setTimeout. Four differences bite:

  • Context-bound lifetime. A timer.delay timer is owned by the script that created it and is auto-cancelled when that game object is deleted. A wait straddling the deletion of its own object never resolves.
  • One-frame minimum resolution. Even setTimeout(cb, 0) / wait(0) fires on the next frame, never the same one — the scheduler is frame-driven, so sub-frame delays round up to one frame.
  • No microtask queue. Promise.resolve().then(...) still runs synchronously on the current call stack; there is no microtask drain. Only a timer-backed promise crosses a frame boundary.
  • Leaked suspended coroutines. A promise that nobody ever resolves leaves its async function suspended forever as a parked Lua coroutine — no error, no warning, no timeout.

ts-defold contrast. ts-defold ships no setTimeout polyfill of its own — its only settimeout is LuaSocket's per-socket I/O timeout method, not a scheduler. The @defold-typescript/types/timers module is specific to this toolchain.

How we pin this in the type tests. packages/transpiler/src/transpile.test.ts transpiles an async/await sample and asserts the lowering (__TS__AsyncAwaiter for the function, __TS__Await for the await) with zero diagnostics, and that the Promise runtime (__TS__Promise) is present in the emitted lualib_bundle. If TypeScriptToLua (TSTL) changed the async lowering or stopped bundling the Promise helpers, the assertions would fail.

URL addressing: same-world objects are relative, socket: crosses worlds

Symptom. A msg.post that reads naturally in TypeScript silently fails to reach its target — the receiver's on_message never fires, and nothing compiles wrong. The same applies to every API that takes a URL string (go.get/go.set, msg.url, factory.create, …). A literal socket copied from a Lua manual example, like "main:/manager#controller", is the usual culprit: it resolves only when the target collection is actually named main.

msg.post("main:/enemy#ai", "alert");            // resolves only if the target collection's Name is "main" — fragile
msg.post("/enemy#ai", "alert");                 // robust: absolute path inside the current world
msg.post("#health", "damage", { amount: 10 }); // sibling component on the same game object

Why. A Defold URL is [socket:][path][#fragment] — three parts, the first optional. The path is the target object's id, the #fragment is the component on it, and an address that starts with / is resolved from the root of the current game world (the bootstrap collection loaded at game start). The socket: segment names which game world the target lives in, and it earns its keep only with collection proxies: a world's socket name is the Name property of its collection file — "The new world gets its name from the Name property in the collection file." The bootstrap collection is named the same way (it too is given a unique name from its Name property), so there is no special socket you address it through — inside that one world you never write the socket: segment at all. The trap is that a collection's Name is a property distinct from its folder: the editor's main/main.collection is a file path, while the Name you address the world by is a separate field (commonly the project default default, not main). So a literal "main:…" borrowed from a manual example breaks the moment your bootstrap collection is named anything other than main. The two-arg form msg.url(socket, path) is a separate runtime trap: the engine accepts no argument, one argument (a string, Hash, Url or undefined), or three arguments, so msg.url("main", "camera") is a runtime error. The three-arg form always passes three arguments, and any of them may be undefined — an explicit undefined reaches the engine as a passed nil, so the call never drops to two arguments, and an undefined socket addresses the current game world. One combination type-checks but still raises: a socket and fragment with an undefined path fails with Can't resolve id with specified socket and fragment. The tightened msg.url overloads in packages/types/src/msg-overloads.d.ts reject the two-arg call at compile time, so the typings are the warning.

Typed alternative. For anything in the same world (everything in your bootstrap collection) address it without a socket: "camera" (a sibling instance by id, relative to the current component), "/camera" (the same instance by id, absolute from the world root), or "#health" (a sibling component on the same game object). Reserve socket: for reaching into a collection-proxy-loaded world, and pass the target collection's Name — the collection-proxy manual's own cross-world example is msg.post("mylevel:/myobject", "hello"), where mylevel is the loaded collection's Name, not the proxy component's id. For msg.url, use one of the three typed overloads — msg.url() (the current message's url), msg.url("main:/manager#controller") (a string, Hash, Url or undefined), or the three-position msg.url(hash("level1"), hash("/door"), hash("script")), whose positions may each be undefined, an undefined socket meaning the current world — never the two-arg form.

How we pin this in the type tests. packages/types/test-d/msg-url-arity.ts asserts the tightened msg.url overloads. msg.url(), the one-argument string, Hash, Url and undefined forms, and three-argument calls with undefined in any position type-check. Both two-argument calls (msg.url("main", "camera") and msg.url(undefined, hash("/door"))) and msg.url(42) carry @ts-expect-error, so the runtime-invalid forms are rejected at compile time; widen the overloads to accept one and the expected error vanishes, failing the typecheck gate.

A vector's size is v.length(), and url.path can be undefined

Symptom. Reading v.length on a vmath.vector or buf.length on a buffer, or passing url.path or url.socket where a Hash is expected, fails to compile.

const v = vmath.vector([1, 2, 3]);
const size: number = v.length(); // compiles to `#v`
v[1] = 0.5; // 1-based, passed to Defold unchanged

const buf = buffer.create(4, [{ name: hash("rgb"), type: buffer.VALUE_TYPE_UINT8, count: 3 }]);
const count: number = buf.length(); // compiles to `#buf`, the element count

const url = msg.url("main:");
const path = url.path; // Hash | undefined: a socket-only address has no path
if (path !== undefined) {
  print(hash_to_hex(path));
}

Why. A vmath.vector, a buffer and a URL are engine userdata, and their metatables decide what each access does. The vector's __index accepts only integer keys, so v.length raises at runtime; its size comes from the __len metamethod, which v.length() compiles to. Its index is 1-based, as in Lua, and the transpiler passes it through unchanged. A buffer's __len returns its element count, which buf.length() compiles to. A URL's __index returns nil for any unset field. msg.url("main:") or the three-argument form with an undefined path leaves path unset. socket is unset on the sender of an engine message posted with no sender, such as ray_cast_response and ray_cast_missed from physics.raycast_async, animation_done from a model.play_anim with no callback, and window_resized in a render script, and after url.socket = undefined.

Typed alternative. Call v.length() and buf.length(), and check url.socket, url.path and url.fragment against undefined before use. All three URL fields are writable: assign a Hash or a string, or undefined to clear the field.

How we pin this in the type tests. packages/types/test-d/userdata-fields.ts marks v.length and buf.length as fields and url.path and url.socket as a Hash with @ts-expect-error, and compiles buf.length() and url.socket = undefined. packages/transpiler/src/vector-math-emit.test.ts snapshots v.length() as #v and v[1] = 2 with its index unchanged.

A file-level name can hide a Lua or Defold global

Symptom. A file declares a top-level helper named after a Lua global and uses it as intended, yet other code in the same file breaks at runtime:

function select(items: string[]): string | undefined {
  return items[0];
}

export const first = select(["a", "b"]);
export const stop = string.find("hello", "l")[1];

The second line compiles to select(2, string.find("hello", "l")), which calls the helper above instead of Lua's select.

Why. A top-level name you do not export compiles to a Lua local that covers the whole file: a function, a const or let (destructured names included), a class, an enum, or an import binding the file reads as a value. TypeScriptToLua renames such a local only when it clashes with a short list of its own (print, type, pairs, tostring, require and a few more). next, select, tonumber, setmetatable and every Defold namespace (go, timer, label, ...) keep their names, so the local hides the global for the rest of the file, including the Lua the build generates there. An enum go emits local go = go or ({}), which picks up the engine's go table and writes the enum's members into it.

What warns. build and watch print a warning naming the file, line, column and name, and the editor marks the name; the build still succeeds. Nothing warns for:

  • an exported name, which TypeScriptToLua keeps on the module table;
  • a name inside a function body, which hides the global only inside that function, as it does in TypeScript;
  • a const enum or a declare, which emit nothing;
  • an import the build drops: one the file never reads as a value, or a defineScript-style factory import, which the build erases;
  • a file with no import or export, whose top-level names are globals rather than locals.

What to do instead. Rename the declaration: pick instead of select, Mode instead of go.

How we pin this. packages/transpiler/src/lua-global-shadows.test.ts builds each declaration form and each exempt case; packages/cli/src/build.test.ts and packages/cli/src/build-session.test.ts check the warning line build and watch print.

npm packages do not resolve — vendor the source instead

Symptom. You bun add a package and import it by its bare name. The build fails with two errors — one from the Lua require resolver, one from TypeScript:

defold-typescript build: 2 file(s) failed:
  <project>: Could not resolve lua source files for require path 'pure-pkg' in file src/main.ts.
  src/main.ts:1:23: Cannot find module 'pure-pkg' or its corresponding type declarations.

This happens for every npm package, including a dependency-free one that uses nothing but plain TypeScript. The failure is loud, never silent: every non-warning diagnostic is fatal, so the build stops here.

Why. The CLI does not compile your project from disk. runBuild (packages/cli/src/build.ts) globs only the files matched by your tsconfig.json include patterns into an in-memory map and compiles that virtual program. The compiler host serves content for those files, the TypeScript lib.* files, and the language extensions — and nothing else. node_modules is never read, so the package's .d.ts is invisible and the import cannot type-check.

The Lua side fails independently: TypeScriptToLua's node_modules require resolver only accepts .lua files and enforces the extension, so a bare specifier like "pure-pkg" never matches. A package that ships .lua alongside its .d.ts does not work either — it fails with the same two errors, and even on a resolver hit the build writes Lua only for include-matched sources, so dependency Lua would never reach your output.

What to do instead. Copy the source into your project, under a path your include already covers, and import it relatively:

// before — never resolves
import { clamp } from "pure-pkg";

// after — src/vendor/pure-pkg.ts is compiled like any other source file
import { clamp } from "./vendor/pure-pkg";

The scaffold configures no outDir, so generated Lua lands next to its source: that emits src/vendor/pure-pkg.lua, beside the src/main.ts.script your entry point compiles to. Three things to know:

  • The scaffold's include is ["src/**/*.ts"]. Vendored source must sit under an include base or it is never compiled at all.
  • The output path strips the longest matching include base, but only when compilerOptions.outDir names a directory other than "." — an absent outDir, "", and "." all mean alongside output, where the tree mirrors the source tree exactly and nothing is stripped. With an outDir of "out" and ["src/**/*.ts", "vendor/**/*.ts"], vendor/pure-pkg.ts lands flattened at out/pure-pkg.lua — in the outDir root, where it can collide with a src/ name. Vendoring under src/vendor/ keeps the folder in the output either way.
  • Routing the vendored code back through node_modules — a workspace package or a file: dependency — reintroduces the no-resolve failure. The import has to stay relative.

For Defold engine features and third-party Defold libraries, do not look on npm at all: the engine namespaces are ambient from @defold-typescript/types, and native-extension APIs come from resolve, which generates importable modules from your game.project dependencies.

How we pin this. packages/docs-site/app/lib/guide-links.test.ts resolves every cross-page link and #anchor in the guide against the heading ids the site renderer actually emits — so renaming this heading without retargeting the links that point at it, including the TypeScript vs Lua cross-links, fails the gate.

Footnotes

  1. src/ is this guide's shorthand and the scaffold's default, not a fixed location. Your source roots are the include globs in tsconfig.json — ["src/**/*.ts"] out of the box, and any list of folders you set; build and watch compile exactly what those globs match, and ignore exclude. ↩

On this page