Build your Defold game in TypeScript and get VSCode's full editor experience — autocomplete, inline type errors, and safe refactors — across the whole Defold API, while still shipping the plain Lua the engine runs.
Defold versions supported: 1.12.4, 1.13.0, 1.13.1, 1.13.2, 1.14.0, 1.14.1
Note
Want to help shape v1.0? Nothing is locked in yet, and the project ships often — see the changelog. Use it on a real project and open an issue about whatever you hit: a missing or mistyped API, a rough edge in the tooling, docs that left your coding agent guessing, or what you would want built next. Pull requests stay closed until the release.
- The full Defold API, typed — every module and namespace is typed from the official reference, so
go,gui,vmath,msg, and the rest autocomplete and type-check as you write, with the reference documentation rendered into the hover text. - Compiles to plain Lua — your TypeScript runs through the battle-tested TypeScriptToLua (TSTL) compiler down to the Lua Defold already runs: no engine fork, no proprietary runtime, no lock-in.
- Typed scripts end to end —
self,on_message, andon_inputpayloads are typed throughdefineScript,defineGuiScript, anddefineRenderScript, and an editor property declared indefineScript'spropertiesfield lands onselfwith its own type while the toolchain emits thego.propertyregistration for you;defineEditorScripttypes the editor extensions themselves. - The editor completes what your project declares — game-object paths, component ids, node ids, animation ids, resource paths,
game.projectconfig keys, and input action ids are read from your own project files and offered inside the string that needs them. - Pin the API to the engine you ship — lock a project to a Defold release so the types match the runtime you build against, and wall a directory to one script kind so its files see only the surface that kind really has.
- Community libraries, typed on demand — declare a supported library as a dependency and
resolvematerializes its types; each one is maintained here against a pinned upstream rather than scraped at install time. - Hierarchical state machines, built in —
hsmis a typed Hierarchical State Machine library that ships with the toolchain, with no separate install: nested states, timers, history, and parallel regions drive game flow and per-object behavior, while events, their payloads, the context, and every state path are checked at compile time and the editor suggests paths and event types as you type; a hands-on tutorial starts from zero, andviewruns a machine from source in your browser. - Entity systems, built in —
ecsis a typed port of tiny-ecs that ships with the toolchain and compiles to plain Lua with nolualib_bundle: systems run one loop over every entity whose components match their filter, the compiler knows which components each system's entities have, a bridge tohsmlets a state's hooks move an entity in and out of systems, and a hands-on tutorial starts from zero. - Fits new and existing projects — scaffold from scratch, or add the TypeScript surface to a project that already has
game.projectand adopt type safety gradually, one script at a time alongside your existing Lua.- Preserves your project layout — TypeScript blends into the existing project structure without creating a wrapper folder.
- Built for the real loop —
watchrecompiles beside the Defold editor, live transpile diagnostics surface errors inline, and source maps let you set breakpoints in your.ts;--hot-reloadpushes each successful rebuild into the running game, whose runtime errors arrive in your terminal naming the.tsline that threw.
This guide shows how to scaffold a project, write TypeScript that the toolchain compiles to Lua, and look up the language-and-toolchain quirks you will hit along the way.
The sections below mirror the top navigation; each lists the pages in its left-sidebar order. The repository README.md is generated from this file so the GitHub landing page and docs homepage stay aligned.
- Getting started — install Bun, scaffold a new project with
bunx @defold-typescript/cli@latest init path/to/project, add TypeScript to an existing Defold project withinit ., write a one-screen script, and build to Lua withbunx @defold-typescript/cli build. - Editor setup — open the project in VSCode, use the generated
tsconfig.json, and runbunx @defold-typescript/cli watchbeside the Defold editor. - Defold editor — install Defold, open the generated project folder, attach a compiled script (
.ts.script,.ts.gui_script, or.ts.render_script) to its game object, GUI scene, or render pipeline, and run the game (TypeScript is transpiled to Lua by the CLI, not the editor).
- Build Tetris — build a complete Tetris game from scratch: write TypeScript, compile it to Lua, and wire the scene in the Defold editor, seeing the whole workflow end to end.
- Vectors and rotations — the math behind movement, one game problem at a time: positions, vectors, speed, dt, rotation, the dot product, and local versus world space, ending with a ship that drifts through space.
- State machines, one click at a time — a hands-on first look at
hsmfor readers who have never used a state machine: one robot buddy machine grows lesson by lesson, each change shown as a diff, with live diagrams you drive with buttons, from two states through everyhsmfeature to a second machine on its own game object. - Entity systems, one system at a time — a hands-on first look at
ecsfor readers who have never used an entity system: one night garden of fireflies grows lesson by lesson, each change shown as a diff, from a first world through everyecsfeature to a state machine in each firefly.
- TypeScript vs Lua — the Lua-developer on-ramp: a cheat sheet that translates syntax, tables, modules, and the standard library from Lua to the TypeScript the toolchain expects.
- TypeScript gotchas — the canonical catalog of TS / TypeScriptToLua (TSTL) / Defold sharp edges: what each symptom looks like, why the toolchain behaves that way, and the workaround to reach for — from unary minus on a vector silently producing
numberto npm packages not resolving at all. - Data structures — what's built in for Defold:
Array, tuple,Map,Set,WeakMap,WeakSet, object record, andclass, each with its Lua lowering andlualibcost, plus the not-available list (regex,BigInt,LinkedList) and what to reach for instead. - Lua table constructs — how to write a table the engine reads by constant key, such as
render.clear's buffer table: why the object literal doesn't compile, the checkedLuaMaproute and the inline cast, and the mapped type that looks like the fix but silently accepts a wrong key.
- Script lifecycle — type
self,on_message, andon_inputpayloads withdefineScript,defineGuiScript, anddefineRenderScript. - Messages — the
BuiltinMessagescatalog,msg.postsend-side payload narrowing, and theisMessage/onMessagereceive-side helpers. - Where script state lives — the four state tiers — per-instance
self, a shared module local, a cross-script module singleton, and VM-globaldeclare global— each grounded in the emitted Lua. - Vector math — the method-form arithmetic surface (
add,sub,mul,div,unm) onVector3,Vector4,Quaternion, andMatrix4, plus why you cannot writev3 + v3. - Editor scripts — extend the Defold editor with
defineEditorScript; the<name>.ts.editor_scriptartifact, auto-load discovery, and theEditorCommandshape. - State machines — import the typed
hsmlibrary from@defold-typescript/types/hsm, learn how its events, transitions and timers run, define machines in plain modules, run one instance per object onself, and turn Defold messages and engine callbacks into typed events. - Entity systems — import the typed
ecslibrary from@defold-typescript/types/ecs: entities as plain tables, filters that narrow components, the four system factories, the order one world update runs in, and running a world from a script. - ecs and hsm together — one table as both an entity and a machine's
ctx:member,join,leaveandtickMachinesmove entities in and out of systems from state hooks, and when a membership change shows.
- init — scaffold a new Defold project with a TypeScript surface, or add TypeScript to an existing project; the two modes, the
--template/--forceflags, and the starter templates. - init-agents — write the agent contract (
AGENTS.md+CLAUDE.md) into a project that has none, or restore a managed block you edited away; what the block carries, why re-runs never clobber your own notes, and how it differs from the contractinitandupgradealready keep current. - upgrade — move the project to the latest toolchain with one verb (
bunx @defold-typescript/cli@latest upgrade, or itsupdatesynonym): what it re-scaffolds, why it never clobbers your own scripts, what it does to an existingdefold-targetpin, and the--jsonenvelope to read. - set-target — write the
defold-targetpin: a fixed version, a release channel (stable/beta/alpha), or--detectedto sync it to the detected Defold editor, with the typo caught at write time rather than at build time. - watch — the incremental rebuild loop: recompile Lua on every save beside the Defold editor, push each successful rebuild into the running game with
--hot-reload, and re-resolve the extension surface ongame.projectchanges. - reload — push one reload into the running game and read the editor console for a bounded window, so a script learns whether an error surfaced there instead of trusting the editor's "queued" response.
- build — one-shot transpile of every
src/1 TypeScript file to Lua, plus the headlessdefoldsubcommand that drivesbobto build and bundle the project. - run — launch the compiled project from
build/default(or a native-extensiondmengine) with no transpile and no Bob, forwarding engine args after--and propagating the engine exit code. - bob — drive Defold's headless
bob.jarbuild tool: theresolve/build/bundle/status/runsubcommands, the sha-keyed jar cache, Java resolution, and target selection. - wall — opt-in per-directory API walls that narrow a single-kind source directory to its script-kind surface, in interactive and flag forms.
- resolve — generate importable TypeScript modules from your
game.projectnative-extension dependencies, with pin/drift detection and a--frozenlockfile mode. - scene-types — generate the scene-address declaration from your
.collection/.gofiles so game-object paths and component ids complete in the editor; howbuildandwatchkeep it current, howinitandupgradewire it into your program, and why it can never reject an address. - view — run a file's state machines and entity worlds in a local browser viewer from source: active states highlighted in the code, systems with their entities and timings, events, Play and Step, an editable ctx, a log, and live reload on every save.
- library — check a directory of library data the way this CLI reads it: the reader, the print of every module, and one compile of the printed declarations, native declarations and usage examples against this CLI's engine types, with one
<library>: <check>: <message>line per problem and a non-zero exit.
- Transpile diagnostics — the scaffolded
@defold-typescript/tstl-pluginlanguage-service plugin that surfaces TypeScript-to-Lua transpile errors live in the editor, advisory-only and never blockingtsc --noEmit. - Debugging — step through
.tssource with breakpoints via the Local Lua Debugger and the scaffolded Bun launch path (no shell, Windows-native), resolving through the emitted<name>.ts.script.map. - Agent runbooks — harness-neutral procedures for driving the CLI from an automated agent: scaffold a project, install the agent contract, regenerate extension types, add and attach a script (build, wire the compiled component, verify), and fix the Lua output over the
--jsonenvelope, gating onok. - Helper scripts — where build, codegen, and maintenance scripts live: a project-root
/scriptsfolder run with Bun, typed by their ownscripts/tsconfig.json, kept off the Lua build path and out of the Defold-typedsrc/surface. - Test with Bun — where a test goes (next to its module, or in
src/test/when it needs Bun's runtime), how to write and type-check it, and how to test game logic without the engine. - Terminal output — how failure lines read (
defold-typescript <command>: error: <message>), when theerrorword is colored, and how--no-color,NO_COLOR,TERM=dumb, and--jsonturn color off.
- Pinning the Defold target — keep the default latest surface, or pin a fixed version or release channel (
stable/beta/alpha) whose API surface is generated on the fly and materialized into a project-local.defold-types/<version>@<toolchain>/. - Upgrading the toolchain — move the project to the latest toolchain with one verb (
bunx @defold-typescript/cli@latest upgrade, or itsupdatesynonym): what it re-scaffolds, why it never clobbers your own scripts, what it does to an existingdefold-targetpin. - Upgrading Defold versions — move a project between pinned surfaces, with a section per release.
- Native extensions — declare an extension in
game.project[dependencies], then runresolveto generate a@globalTablemodule per.script_apiinto a gitignored.defold-types/extensions/surface, and import it by its namespace. - Shipping types with a library — for library authors: put
.d.tsfiles in a roottypes/folder, use@defold-typescript/typesnames, choose the module or global form, check the result withresolve, which installs them ahead of every other surface, and start from the curated types withexport-types. - Adding a library to the library data: the library docs site covers LuaLS library types, forked library types and refreshing library pins.
- API docs vs
ts-defold-types— a factual, dimension-by-dimension comparison of the JSDoc that@defold-typescript/typesandts-defold-typesemit (Markdown conversion, dash params, grid-aligned multi-line docs, branded constants, the@exampletrade-off), with a picker for which surface fits your project. - Migrating from
ts-defold— move a project off the@ts-defold/*stack: the package/tooling map, the step-by-step port viainitadd-TypeScript mode and atsconfig.jsonreconcile, and the type-surface differences you will hit.
- Changelog — what changed in each published toolchain version (
vX.Y.Ztag), reverse-chronological withAdded/Improved/Fixedand aBreakinglead line where behavior changed incompatibly; the latest releases per-patch, older ones rolled up per minor.
- API — the generated
@defold-typescript/typesreference: every documented Defold namespace, grouped alphabetically as cards (site-only; built from the typed surface the toolchain ships). - Lua standard library — the pure-Lua / LuaJIT reference category (
base,bit, …). Types are owned by thelua-typesdependency thelua-stdlib-globalsgoal adopted;@defold-typescript/typesdoes not re-emit them as generated namespaces. - For AI agents — machine-readable docs per llmstxt.org:
llms.txtis the map (start here)llms-full.txtis the full corpus (grep it, never read it whole). The same pair ships into a consumer'snode_modules/@defold-typescript/docs/on install.init-agentswires them up — it writes the managedAGENTS.md/CLAUDE.mdblock that points your agent at both files and at the runbooks, so a fresh session orients from the project's own documentation instead of from training-data recall.
Language and platform logos come from Devicon, MIT License, Copyright (c) 2015 konpa (license). Other interface icons come from Phosphor Icons, MIT License, Copyright (c) 2023 Phosphor Icons (license). Logos are trademarks of their respective owners and indicate compatibility only.
Footnotes
-
src/is this guide's shorthand and the scaffold's default, not a fixed location. Your source roots are theincludeglobs intsconfig.json—["src/**/*.ts"]out of the box, and any list of folders you set;buildandwatchcompile exactly what those globs match, and ignoreexclude. ↩
