### Initialize roblox-ts Project Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/quick-start.mdx Run this command to start the interactive project setup tool for roblox-ts, guiding you through the initial configuration of your new project. ```Shell npm init roblox-ts ``` -------------------------------- ### Setup roblox-ts Documentation Local Development Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/README.md This snippet provides the necessary commands to install dependencies and start the local development server for the roblox-ts documentation website. Changes are reflected live without server restarts. ```Shell npm install npm start ``` -------------------------------- ### Start Rojo Server for Syncing Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/setup-guide.mdx Launches the Rojo server, which synchronizes compiled roblox-ts code from the local file system into Roblox Studio. This enables live updates and rapid iteration during game development. ```bash rojo serve ``` -------------------------------- ### Open Project in VSCode Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/setup-guide.mdx Opens the specified project directory in Visual Studio Code. This command assumes that VSCode is installed and configured to be accessible from the command line. ```bash code project-name ``` -------------------------------- ### Build and Start roblox-ts Interactive Playground Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/README.md These commands guide the user through setting up and launching the interactive playground. It involves navigating to the worker directory, installing its specific dependencies, and then running the playground server. ```Shell cd ./rbxts-worker npm install cd .. npm run start:playground ``` -------------------------------- ### Start roblox-ts Watch Mode Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/setup-guide.mdx Initiates roblox-ts's watch mode, which continuously monitors source files for changes and automatically recompiles the project. This is essential for a smooth development workflow. ```bash npm run watch ``` -------------------------------- ### Start Rojo Server Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/quick-start.mdx Use this command to start the Rojo server. Rojo facilitates live synchronization between your local project files and Roblox Studio, allowing for rapid iteration and development. ```Shell rojo serve ``` -------------------------------- ### Initialize roblox-ts Project with npm Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/setup-guide.mdx Initializes a new roblox-ts project in the current directory using npm. The command prompts the user for various configuration options, including project directory, template, Git integration, ESLint, Prettier, and VSCode settings. ```bash npm init roblox-ts ``` -------------------------------- ### Start roblox-ts Watch Mode Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/quick-start.mdx Execute this command to start the roblox-ts compiler in watch mode. This automatically recompiles your TypeScript code into Lua whenever file changes are detected, ensuring your project stays up-to-date. ```Shell npx rbxtsc -w ``` -------------------------------- ### Test roblox-ts package locally using npm pack Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/typescript-packages.mdx These commands allow you to create a local `.tgz` archive of your package and then install it into another project for testing purposes, simulating a real npm installation. ```Shell npm pack npm install ../../path/to/package.tgz ``` -------------------------------- ### Set PowerShell Execution Policy Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/setup-guide.mdx This command addresses a common PowerShell error preventing script execution by setting the execution policy to 'RemoteSigned' for the current user, allowing locally created scripts to run. ```powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser ``` -------------------------------- ### Importing Luau Module Static Fields (TypeScript) Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/using-existing-luau.mdx This example demonstrates how to import specific static fields from a Luau module into a TypeScript file. This approach is used when the Luau module's type definition provides named exports for its properties. ```ts import { Foo, Secret } from "./MyConstants"; print(Foo, Secret); ``` -------------------------------- ### Example: npm publish 402 Payment Required Error Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/faq/publish-as-public.mdx An example of the '402 Payment Required' error message displayed in the console when attempting to publish a private package to npm without a paid organization subscription. ```sh npm error code E402 npm error 402 Payment Required - PUT https://registry.npmjs.org/@rbxts%2fpackage - You must sign up for private packages ``` -------------------------------- ### Roact JSX: Extending Intrinsic Elements for Custom Roblox Instances Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/roact-jsx.mdx This example demonstrates how to extend the global `JSX` namespace to enable direct JSX creation of custom Roblox instances like `ProximityPrompt` and `Folder`. It ensures proper type inference for their properties and events, recommending a centralized definition. ```tsx declare global { namespace JSX { interface IntrinsicElements { // Your instances into here proximityprompt: JSX.IntrinsicElement; folder: JSX.IntrinsicElement; } } } ``` -------------------------------- ### Importing Luau Module with Export Assignment (TypeScript) Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/using-existing-luau.mdx This example shows how to import a Luau module into a TypeScript file when its type definition uses an 'Export Assignment'. The module is imported as a default export, allowing direct access to its defined members. ```ts import Module from "./Module"; print(Module); ``` -------------------------------- ### Accessing a deeply nested typed child Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/indexing-children.mdx This example shows how to access a deeply nested child, `Workspace.Zombie.Humanoid`, after its type has been defined in `src/services.d.ts`. This ensures type safety and provides autocompletion for properties within `Zombie`. ```TypeScript // some other file import { Workspace } from "@rbxts/services"; // highlight-start print(Workspace.Zombie.Humanoid); // highlight-end ``` -------------------------------- ### Automatically generated complex type definition for ReplicatedStorage Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/indexing-children.mdx This large TypeScript type definition demonstrates an example of a `ReplicatedStorage` interface automatically generated by the 'rbxts-object-to-tree' plugin. It includes a `Zombie` model with multiple nested parts and properties, showcasing how complex DataModel structures can be fully typed. ```TypeScript interface ReplicatedStorage extends Instance { Zombie: Model & { ["Left Leg"]: Part; Humanoid: Humanoid; ["Right Leg"]: Part; Head: Part & { Mesh: SpecialMesh; Face: Decal; }; Torso: Part; HumanoidRootPart: Part; ["Right Arm"]: Part; ["Left Arm"]: Part; ["Body Colors"]: BodyColors; }; } ``` -------------------------------- ### Destructuring LuaTuple Result in TypeScript Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/lua-tuple.mdx An example demonstrating how immediate destructuring of a function call that returns a `LuaTuple` compiles into an efficient variable declaration from a multiple return in Luau, avoiding intermediate array creation. ```ts const [actualTimeYielded, totalTime] = wait(1); ``` -------------------------------- ### Use Generic Function with Roblox Instance Types Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Provides an example of a generic TypeScript function `getDescendantsWhichIsA` that leverages the `Instances` type to filter descendants of an `Instance` by a specified class name, returning a type-safe array of matching instances. This demonstrates practical application of the defined type interfaces. ```ts import { Workspace } from "@rbxts/services"; function getDescendantsWhichIsA(parent: Instance, className: T): Instances[T][] { return parent.GetDescendants().filter((descendant): descendant is Instances[T] => descendant.IsA(className)); } const humanoidsInWorkspace: Array = getDescendantsWhichIsA(Workspace, "Humanoid"); ``` -------------------------------- ### Initialize a new roblox-ts package project Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/typescript-packages.mdx Use this command in an empty folder to generate the basic scaffolding for a new roblox-ts package, including source and output directories. ```Shell npm init roblox-ts package ``` -------------------------------- ### Configure Rojo for StarterCharacterScripts in roblox-ts Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/syncing-with-rojo.mdx This JSON snippet demonstrates how to extend the default.project.json file to include a new path for StarterCharacterScripts. It shows how to map compiled Luau files from the out/character directory into the StarterPlayer.StarterCharacterScripts service within Roblox Studio, allowing for character-specific scripts. ```json "StarterPlayer": { "$className": "StarterPlayer", "StarterPlayerScripts": { "$className": "StarterPlayerScripts", "TS": { "$path": "out/client" } }, "StarterCharacterScripts": { "$className": "StarterCharacterScripts", "TS": { "$path": "out/character" } } } ``` -------------------------------- ### Default Rojo Project Configuration for roblox-ts Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/syncing-with-rojo.mdx This JSON snippet illustrates the typical structure of a default.project.json file used with roblox-ts projects. It defines how compiled Luau files from out/server, out/shared, and out/client directories are mapped to specific services within Roblox Studio, such as ServerScriptService, ReplicatedStorage, and StarterPlayerScripts. It also shows the required rbxts_include and node_modules paths. ```json { "name": "roblox-ts-game", "tree": { "$className": "DataModel", "ServerScriptService": { "$className": "ServerScriptService", "TS": { "$path": "out/server" } }, "ReplicatedStorage": { "$className": "ReplicatedStorage", "rbxts_include": { "$path": "include", "node_modules": { "$path": "node_modules/@rbxts" } }, "TS": { "$path": "out/shared" } }, "StarterPlayer": { "$className": "StarterPlayer", "StarterPlayerScripts": { "$className": "StarterPlayerScripts", "TS": { "$path": "out/client" } } } } } ``` -------------------------------- ### Print 'Hello World!' using Roblox-TS Globals Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Demonstrates the use of the global `print` function available in roblox-ts typings, mirroring the Roblox API's global functions for basic output. ```typescript print("Hello World!"); ``` -------------------------------- ### roblox-ts CLI Reference Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/usage.mdx This section details the command-line interface for roblox-ts, a TypeScript-to-Luau compiler for Roblox. It lists the main commands and a comprehensive set of options to control compilation, watch mode, logging, and file inclusion. ```APIDOC roblox-ts - A TypeScript-to-Luau Compiler for Roblox Commands: rbxtsc build Build a project [default] Options: -p, --project project path [string] [default: "."] -w, --watch enable watch mode [boolean] [default: false] --usePolling use polling for watch mode [boolean] [default: false] --verbose enable verbose logs [boolean] [default: false] --noInclude do not copy include files [boolean] [default: false] --logTruthyChanges logs changes to truthiness evaluation from Lua truthiness rules [boolean] [default: false] --writeOnlyChanged [boolean] [default: false] --writeTransformedFiles writes resulting TypeScript ASTs after transformers to out directory [boolean] [default: false] --optimizedLoops [boolean] [default: false] --type override project type [choices: "game", "model", "package"] -i, --includePath folder to copy runtime files to [string] --rojo manually select Rojo project file [string] --allowCommentDirectives [boolean] [default: false] -h, --help show help information [boolean] -v, --version show version information [boolean] ``` -------------------------------- ### Map Constructor Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/constructors.mdx Creates a new `Map` type pre-filled with the entries given as the argument if provided. Compiles to a table literal. ```APIDOC new Map(entries?: Array<[K, V]>) entries: Optional array of key-value pairs to pre-fill the map with. Compiles to: table literal ``` -------------------------------- ### Exclude Nominal Members from Type in TypeScript Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/utility-types.mdx The `ExcludeNominalMembers` TypeScript type utility creates a new object type from `T` by excluding all keys that start with `_nominal_`. It uses `Pick` in conjunction with `ExcludeNominalKeys` to filter out these specific members, which are often used for type branding or internal mechanisms. ```TypeScript type ExcludeNominalMembers = Pick>; ``` -------------------------------- ### Luau Module Return Pattern Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/using-existing-luau.mdx This Luau snippet demonstrates the standard pattern for a module script to return a single value, typically a table, which encapsulates its functionality. This returned table is then accessible when the module is required. ```lua local Module = {} -- define Module members return Module ``` -------------------------------- ### Use Custom Rojo Project File with roblox-ts Compiler Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/syncing-with-rojo.mdx This command demonstrates how to specify an alternative project.json file for roblox-ts to use during compilation, overriding the default default.project.json. This is useful for managing different project configurations. ```bash rbxtsc --rojo other.project.json ``` -------------------------------- ### WeakMap Constructor Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/constructors.mdx Same as `new Map`, but creates a `WeakMap` type instead. Compiles using `setmetatable({}, { __mode = "k" })`. ```APIDOC new WeakMap(entries?: Array<[K, V]>) entries: Optional array of key-value pairs to pre-fill the map with. Compiles to: setmetatable({}, { __mode = "k" }) ``` -------------------------------- ### Roact JSX: Shorthand Syntax for Fragments Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/roact-jsx.mdx This snippet presents the concise shorthand syntax (`<>...`) for creating Roact Fragments in JSX. It serves the same purpose as `Roact.Fragment` but offers a more compact and readable alternative. ```tsx import Roact from "@rbxts/roact"; const fragment = <>; ``` -------------------------------- ### roblox-ts package.json Configuration Fields Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/typescript-packages.mdx Defines the essential fields within the `package.json` file for configuring a roblox-ts package, including naming conventions, entry points, and metadata required for proper publishing and functionality. ```APIDOC package.json fields: "name": string Description: Must begin with "@rbxts/" to be considered a valid roblox-ts package. "description": string Description: A brief description of the package. "main": string Description: Points to a .lua file in 'out' which represents your package's entrypoint. "typings": string Description: Points to a .d.ts file in 'out' which represents your package's entrypoint. "files": string[] Description: An array of globs for what should be published to npm. Defaults to ["out"]. "repository": string Description: If your package's source is public, include a link to it (e.g., GitHub). "homepage": string Description: If your package has online documentation, include a link to it. "author": string Description: Your own name or username. "license": string Description: The SPDX license identifier corresponding to your LICENSE file. ``` -------------------------------- ### TypeScript Method: Object Method Declaration Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/callbacks-vs-methods.mdx Shows how a concise method declaration within an object literal is treated as a method, compiling to `:` notation in Luau. ```TypeScript const obj = { foo(bar: number) {} } obj.foo(123); // obj:foo(123) ``` -------------------------------- ### Set Constructor Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/constructors.mdx Creates a new `Set` type pre-filled with the values given as the argument if provided. Compiles to a table literal. ```APIDOC new Set(values?: Array) values: Optional array of values to pre-fill the set with. Compiles to: table literal ``` -------------------------------- ### Promise Constructor Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/constructors.mdx Creates a new `Promise` type. Documentation for the promise library that comes bundled with roblox-ts can be found [here](https://eryn.io/roblox-lua-promise/). ```APIDOC new Promise() ``` -------------------------------- ### Publish Package with Public Access CLI Flag Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/faq/publish-as-public.mdx Use the '--access public' flag directly with the 'npm publish' command. This explicitly publishes the package as public, overriding any default private settings and preventing the '402 Payment Required' error. ```sh npm publish --access public ``` -------------------------------- ### Creating Roact Elements with JSX and TypeScript Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/roact-jsx.mdx Demonstrates creating Roact UI elements using JSX shorthand and the traditional `Roact.createElement` method in TypeScript. This highlights the syntactic sugar JSX provides for UI construction. ```tsx import Roact from "@rbxts/roact"; const element = ( ); ``` ```ts import Roact from "@rbxts/roact"; const element = Roact.createElement( "Frame", { Size: new UDim2(1, 0, 1, 0), }, { Child: Roact.createElement("Frame", { Size: new UDim2(1, 0, 1, 0), }), } ); ``` -------------------------------- ### WeakSet Constructor Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/constructors.mdx Same as `new Set`, but creates a `WeakSet` type instead. Compiles using `setmetatable({}, { __mode = "k" })`. ```APIDOC new WeakSet(values?: Array) values: Optional array of values to pre-fill the set with. Compiles to: setmetatable({}, { __mode = "k" }) ``` -------------------------------- ### ReadonlyMap Constructor Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/constructors.mdx Same as `new Map`, but creates a `ReadonlyMap` type instead. ```APIDOC new ReadonlyMap(entries?: Array<[K, V]>) entries: Optional array of key-value pairs to pre-fill the map with. ``` -------------------------------- ### Luau Module Returning Table with Static Fields Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/using-existing-luau.mdx This Luau snippet illustrates a module that returns a table containing multiple static fields. This pattern is suitable when individual properties or functions from the module are intended to be imported separately. ```lua local MyConstants = {} MyConstants.Foo = "Bar" MyConstants.Secret = "hunter2" return MyConstants ``` -------------------------------- ### Array Constructor Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/constructors.mdx Creates a new `Array` type with the given preallocated length and pre-filled with `value`. Compiles to either a table literal or a `table.create()` call in Luau. ```APIDOC new Array(length?: number, value?: T) length: Optional number for preallocated length. value: Optional value to pre-fill the array with. Compiles to: table literal or table.create() (Luau) ``` -------------------------------- ### Configure package.json for Public Access Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/faq/publish-as-public.mdx Modify the 'package.json' file to include a 'publishConfig' section with '"access": "public"'. This ensures the package is published as public, bypassing the default private setting for new organization packages and resolving the '402 Payment Required' error. ```js { "name": "@rbxts/package", // your package name goes here "version": "1.0.0", "publishConfig": { "access": "public" } // other fields } ``` -------------------------------- ### Constructing Roblox API Objects with 'new' Operator Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Demonstrates the idiomatic way to create new instances of Roblox API types like `Vector3` and `Instance` using the `new` operator in roblox-ts. This syntax compiles to the traditional `.new()` method calls in Roblox Lua. ```typescript const v3 = new Vector3(1, 2, 3); // compiles to Vector3.new(1, 2, 3) print(v3.X, v3.Y, v3.Z); // 1 2 3 ``` ```typescript const part = new Instance("Part"); print(part.Color); ``` -------------------------------- ### Using TypeScript-Defined Custom OOP Class Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/using-existing-luau.mdx This code demonstrates how to interact with a custom OOP class whose types have been defined in TypeScript. It shows accessing both static properties and methods directly from the class, as well as instance properties and methods after creating an object. ```ts print(MyClass.staticProperty); print(MyClass.staticMethod()); const myClass = new MyClass(); print(myClass.instanceProperty); print(myClass.instanceMethod()); ``` -------------------------------- ### ReadonlySet Constructor Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/constructors.mdx Same as `new Set`, but creates a `ReadonlySet` type instead. ```APIDOC new ReadonlySet(values?: Array) values: Optional array of values to pre-fill the set with. ``` -------------------------------- ### Define Comprehensive Roblox Instances Interface Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Defines the `Instances` interface, which extends `Services`, `CreatableInstances`, and `AbstractInstances`. It includes all Roblox instance types, including those not creatable or fetchable via `GetService` but referenced directly, providing a complete type mapping. ```ts interface Instances extends Services, CreatableInstances, AbstractInstances { AnimationTrack: AnimationTrack; BaseWrap: BaseWrap; CatalogPages: CatalogPages; DataModel: DataModel; // ... many more instances! } ``` -------------------------------- ### npm Organization Join HTML Form Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/src/pages/join-org/index.mdx This HTML form allows users to input their npm username to request an invitation to the '@rbxts' npm organization. It is styled using inline JSX style objects and includes a reCAPTCHA-enabled submit button that calls the `onSubmit` JavaScript function upon verification. ```React/HTML
``` -------------------------------- ### TypeScript Callback: Function Declaration Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/callbacks-vs-methods.mdx Demonstrates how a standalone function declaration assigned to an object property is treated as a callback, compiling to `.` notation in Luau. ```TypeScript function foo(bar: number) {} const obj = { foo: foo }; obj.foo(123); // obj.foo(123) ``` -------------------------------- ### Import and Render RecaptchaLoader Component Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/src/pages/join-org/invite-sent.mdx This snippet demonstrates the import of a custom React component, `RecaptchaLoader`, and its subsequent rendering. This component is likely responsible for dynamically loading the Google reCAPTCHA script and setting up the reCAPTCHA widget on the page. ```JSX import RecaptchaLoader from "../../components/RecaptchaLoader"; ``` -------------------------------- ### Using Math Globals in Roblox-TS Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Illustrates accessing global math functions like `math.sin` and `math.pi` provided by roblox-ts typings, similar to the Roblox API's mathematical utilities. ```typescript const zero = math.sin(math.pi); ``` -------------------------------- ### Coroutine Usage in Roblox-TS Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Shows how to use `coroutine.wrap` for asynchronous operations, demonstrating a common pattern for managing execution flow and delaying actions in Roblox environments. ```typescript coroutine.wrap(() => { print("A"); wait(1); print("B"); })(); ``` -------------------------------- ### Declaring and Instantiating Roblox Types Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Shows how to declare a variable with a specific Roblox class type (e.g., `Part`) and instantiate it using `new Instance()`. This highlights the type safety and inference capabilities provided by roblox-ts. ```typescript // note: The type Part could be inferred here if not provided const part: Part = new Instance("Part"); print(part.Size); ``` -------------------------------- ### Pick Type Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/utility-types.mdx Constructs a type by picking a set of properties K from type T. ```ts type Pick = { [P in K]: T[P] }; ``` -------------------------------- ### Function Parameter Type Inheritance with BasePart Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Demonstrates defining a function that accepts a `BasePart` type as a parameter, showcasing how type inheritance works with Roblox types. This allows the function to accept any object that inherits from `BasePart`, promoting code reusability. ```typescript function takesBasePart(basePart: BasePart) { return basePart.Size.X + basePart.Size.Y + basePart.Size.Z; } // we can use any type which inherits from BasePart! takesBasePart(new Instance("Seat")); takesBasePart(new Instance("Part")); takesBasePart(new Instance("WedgePart")); // Humanoid does not inherit from BasePart, so this will error! // takesBasePart(new Instance("Humanoid")); ``` -------------------------------- ### reCAPTCHA Integration and Form Submission Callback Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/src/pages/join-org/index.mdx This snippet demonstrates the integration of reCAPTCHA within a React application. It imports a custom `RecaptchaLoader` component, renders it, and sets up a global `onSubmit` function. This function is invoked by reCAPTCHA upon successful verification, triggering the submission of the 'org-form' HTML element. ```React/JavaScript import RecaptchaLoader from "../../components/RecaptchaLoader"; <>{(() => globalThis.onSubmit = token => document.getElementById("org-form").submit())()} ``` -------------------------------- ### TypeScript Type Definition for Custom OOP Class Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/using-existing-luau.mdx This TypeScript snippet provides a common pattern for defining types for a custom Object-Oriented Programming (OOP) class. It includes interfaces for both instance members and static members, along with an export assignment for the class constructor. ```ts interface MyClass { instanceProperty: string; instanceMethod(): number; } interface MyClassConstructor { new (): MyClass; staticProperty: string; staticMethod(): number; } declare const MyClass: MyClassConstructor; export = MyClass; ``` -------------------------------- ### Define Creatable Roblox Instances Interface Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Defines the `CreatableInstances` interface, mapping string names to types for Roblox instances that can be created with `Instance.new("ClassName")`. This provides type checking for instance creation. ```ts interface CreatableInstances { Accessory: Accessory; Accoutrement: Accoutrement; Actor: Actor; AlignOrientation: AlignOrientation; // ... many more instances! } ``` -------------------------------- ### Using the `Ref` Attribute in Roact JSX Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/roact-jsx.mdx Demonstrates how the `Ref` attribute in Roact JSX directly maps to the `[Roact.Ref]` key in Luau. This provides a mechanism to obtain direct references to rendered UI instances. ```tsx import Roact from "@rbxts/roact"; const ref = Roact.createRef(); const element = ; ``` -------------------------------- ### Derive All Roblox Instance Names and Types Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Illustrates how to derive a union type of all instance names using `keyof Instances` and a union type of all instance types using `Instances[keyof Instances]`. These comprehensive types are essential for broad type-safe interactions with Roblox instances. ```ts type AllInstanceNames = keyof Instances; type AllInstances = Instances[keyof Instances]; ``` -------------------------------- ### Diagnosing npm E404 Not Found Error During Publish Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/faq/publish-not-found.mdx This snippet shows the typical output of an 'npm error 404 Not Found' when attempting to publish a package that is not found in the registry, often indicating an issue with initial package registration or organization association. ```sh npm error code E404 npm error 404 Not Found - PUT https://registry.npmjs.org/@rbxts%2package - Not found npm error 404 npm error 404 '@rbxts/package@1.0.0' is not in this registry. npm error 404 npm error 404 Note that you can also install from a npm error 404 tarball, folder, http url, or git url. ``` -------------------------------- ### Spreading Objects into Roact JSX Attributes Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/roact-jsx.mdx Demonstrates using the spread syntax (`{...exp}`) to apply properties from an object to Roact JSX attributes. This is useful for creating reusable sets of properties or styles. ```tsx import Roact from "@rbxts/roact"; const MyStyle: Partial> = { BackgroundColor3: new Color3(0, 0, 0), BackgroundTransparency: 0.5, }; const element = ; ``` -------------------------------- ### Using $tuple Macro for Multiple Returns in TypeScript Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/lua-tuple.mdx Demonstrates the `$tuple` macro, a convenient utility in roblox-ts that allows developers to explicitly define functions that compile into Luau multiple returns, simplifying the process and avoiding manual type assertions. ```ts function hasMultipleReturns() { // this will compile into `return "abc", 123` return $tuple("abc", 123); } ``` -------------------------------- ### Accessing a top-level typed child Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/indexing-children.mdx This snippet demonstrates how to safely access the `Workspace.Zombie` property in another file after its type has been defined in `src/services.d.ts`. The `print` statement will now correctly infer `Workspace.Zombie` as a `Model`. ```TypeScript // some other file import { Workspace } from "@rbxts/services"; // highlight-start print(Workspace.Zombie); // highlight-end ``` -------------------------------- ### Define Global reCAPTCHA onSubmit Callback Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/src/pages/join-org/invite-sent.mdx This JavaScript snippet, embedded within a JSX fragment, defines a global `onSubmit` function. This function is designed to be called by the Google reCAPTCHA widget upon successful verification, triggering the submission of the HTML form with the ID 'org-form'. ```JavaScript (() => globalThis.onSubmit = token => document.getElementById("org-form").submit())() ``` -------------------------------- ### Connecting to RemoteEvent OnClientEvent and OnServerEvent Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Illustrates connecting callback functions to `RemoteEvent.OnClientEvent` and `RemoteEvent.OnServerEvent`. It highlights the type safety for client-side events and the default `unknown` type for server-side events due to untrusted client input. ```typescript const remoteEvent = new Instance("RemoteEvent"); // this works fine remoteEvent.OnClientEvent.Connect((points: number) => {}); // changing unknown to number causes an error! remoteEvent.OnServerEvent.Connect((player: Player, points: unknown) => {}); ``` -------------------------------- ### InstanceMethodNames Type Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/utility-types.mdx Given an Instance `T`, returns a unioned type of all method names. ```ts type InstanceMethodNames = ExtractKeys; ``` -------------------------------- ### Extract and Display Error Reason from URL Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/src/pages/join-org/fail.mdx This JavaScript/TypeScript snippet retrieves the value of the 'reason' query parameter from the current page's URL. It is typically used to display a specific error message passed to the page via URL parameters. ```TypeScript new URLSearchParams(globalThis.location?.search).get("reason") ``` -------------------------------- ### Connecting to PropertyChangedSignal Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Shows the recommended way to detect property changes on Roblox instances using `Instance.GetPropertyChangedSignal()`. This is preferred over the deprecated `Instance.Changed` for better type safety and specific property tracking. ```typescript import { Workspace } from "@rbxts/services"; Workspace.GetPropertyChangedSignal("DistributedGameTime").Connect(() => { print(Workspace.DistributedGameTime); }); ``` -------------------------------- ### Define Roblox Services Interface Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Defines the `Services` interface, mapping string names to their corresponding Roblox service types. This interface is used to type `game:GetService("ServiceName")` calls, providing type safety for service access. ```ts interface Services { AnalyticsService: AnalyticsService; AppUpdateService: AppUpdateService; AssetCounterService: AssetCounterService; AssetDeliveryProxy: AssetDeliveryProxy; // ... many more services! } ``` -------------------------------- ### ConstructorParameters Type Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/utility-types.mdx Obtains the parameters of a constructor function type T as a tuple, or `never` if T is not a constructor. ```ts type ConstructorParameters any> = T extends new (...args: infer P) => any ? P : never; ``` -------------------------------- ### Checking Instance Class Names with classIs() in roblox-ts Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/functions.mdx The `classIs(value, "ClassName")` function provides an alternative to `instance.IsA()` for checking an instance's class name. It compiles to `value.ClassName == "ClassName"`, which can be useful in scenarios where `instance.IsA()` might return true for inherited classes (e.g., `LocalScript` is a `Script`), allowing for more precise class identification. ```ts function foo(value: Instance) { // value.IsA("Script") would return true for LocalScripts! if (classIs(value, "Script")) { print(value.Name); } } ``` -------------------------------- ### Derive All Abstract Roblox Instance Names and Types Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Demonstrates how to derive a union type of all abstract instance names using `keyof AbstractInstances` and a union type of all abstract instance types using `AbstractInstances[keyof AbstractInstances]`. These types are useful for operations involving abstract instance categories. ```ts type AllAbstractInstanceNames = keyof AbstractInstances; type AllAbstractInstances = AbstractInstances[keyof AbstractInstances]; ``` -------------------------------- ### Placeholder Type _ Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/utility-types.mdx A placeholder type that sometimes helps force TypeScript to display the desired type information. ```ts type _ = T; ``` -------------------------------- ### Partial Type Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/utility-types.mdx Constructs a type with all properties of T set to optional. ```ts type Partial = { [P in keyof T]?: T[P] }; ``` -------------------------------- ### Spreading Arrays into Roact JSX Children Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/roact-jsx.mdx Illustrates how to use the spread syntax (`{...exp}`) with an array to dynamically add multiple child elements to a Roact JSX component. This is beneficial for rendering lists of components. ```tsx import Roact from "@rbxts/roact"; const listItems = new Array(); for (let i = 0; i < 10; i++) { listItems.push(); } const element = {...listItems}; ``` -------------------------------- ### Handling Property Changes with `Change` Attribute in Roact JSX Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/roact-jsx.mdx Explains how the `Change` attribute takes an object mapping property names to callback functions. These functions are invoked when the corresponding property changes, receiving the UI instance reference. ```tsx import Roact from "@rbxts/roact"; const element = ( print(`${rbx.GetFullName()} changed Position!`), }} /> ); ``` -------------------------------- ### Mapping `Key` Attribute in Roact JSX to Luau Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/roact-jsx.mdx Compares the `Key` attribute in Roact JSX to the traditional Luau `Child` key, demonstrating its role in controlling the UI Instance name within the DataModel for efficient reconciliation. ```lua Roact.createElement("Frame", { Child = Roact.createElement("Frame", {}), }) ``` ```tsx import Roact from "@rbxts/roact"; const element = ( ); ``` -------------------------------- ### Handling Events with `Event` Attribute in Roact JSX Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/guides/roact-jsx.mdx Shows how the `Event` attribute takes an object mapping event names to connection functions. These functions are called when the event fires, receiving the UI instance reference and event-specific arguments. ```tsx import Roact from "@rbxts/roact"; const element = ( print(`${rbx.GetFullName()} was clicked at (${x}, ${y})`), }} /> ); ``` -------------------------------- ### Define Abstract Roblox Instances Interface Source: https://github.com/roblox-ts/roblox-ts.com/blob/master/docs/api/roblox-api.mdx Defines the `AbstractInstances` interface, mapping string names to types for Roblox instances that are never created directly but are useful for inheritance checks like `Instance:IsA("ClassName")`. This helps in typing functions that deal with abstract base types. ```ts interface AbstractInstances { BackpackItem: BackpackItem; BasePart: BasePart; BasePlayerGui: BasePlayerGui; BaseScript: BaseScript; // ... many more instances! } ```