New roblox-ts users often ask, "How can I index a child in the game like
The problem here is that you are making an assumption that
Zombie is something that exists inside
Workspace. In Roblox, if you try to index the child of an instance that does not exist, it results in an error. Even if roblox-ts allowed you to do this,
Zombie would be of type
Instance which is not particularly helpful!
The simplest solution to this problem is to extend the types of your services to describe the state of your DataModel.
We can do this through "ambient type declarations". An ambient type definition file is a
.d.ts file which contains no imports or exports. This file becomes global and the types are available in every file without importing.
We can name this file anything and put it anywhere in
src, but for this example we'll stick to
If you want to define children inside of Zombie, you can do this with an intersection object type:
Writing out long
services.d.ts files is tedious! And a mismatch between your type definition files and actual game could be dangerous.
Luckily, there's an existing plugin by Validark called "rbxts-object-to-tree" that you can use to automatically generate these typings.
- Simply select the service you want to generate typings for in the Explorer pane.
- Click "TS types" and "GENERATE"
- Your type definition file will be created in Lighting and you can copy that over into
Alternatively, to make things even more automatic you can use io-serve by Evaera to automatically write the .d.ts files to your filesystem.
First, make sure HTTP requests are enabled for your game in Game Settings or by running
game.HttpService.HttpEnabled = true in the command bar.
Then, simply just run
npx io-serve in your project folder before hitting "GENERATE" in rbxts-object-to-tree.
npx will automatically download and then run io-serve for you.
This will generate a file located at