### Initialize a new roblox-ts project Source: https://roblox-ts.com/docs/quick-start Run this command to start the interactive project setup tool. ```bash npm init roblox-ts ``` -------------------------------- ### Start watch mode Source: https://roblox-ts.com/docs/setup-guide Continuously build your code as you write it by starting watch mode. ```bash npm run watch ``` -------------------------------- ### Start Rojo Source: https://roblox-ts.com/docs/quick-start Run this command in a separate terminal to start the Rojo server, which synchronizes your project with Roblox Studio. ```bash rojo serve ``` -------------------------------- ### Open project in VSCode Source: https://roblox-ts.com/docs/setup-guide After project initialization, open the project folder in VSCode. ```bash code project-name ``` -------------------------------- ### Start watch mode Source: https://roblox-ts.com/docs/quick-start Run this command to start roblox-ts in watch mode, which automatically recompiles your code when changes are detected. ```bash npx rbxtsc -w ``` -------------------------------- ### Install a local package Source: https://roblox-ts.com/docs/guides/typescript-packages Command to install a package from a local .tgz file. ```bash npm install ../../path/to/package.tgz ``` -------------------------------- ### Luau Module Return Value Source: https://roblox-ts.com/docs/guides/using-existing-luau Example of a Luau script returning a module. ```luau local Module = {} -- define Module members return Module ``` -------------------------------- ### Indexing multiple return immediately Source: https://roblox-ts.com/docs/guides/lua-tuple Example of indexing the result of a function call immediately to get an optimized emit. ```typescript import { Players } from "@rbxts/services"; // .Wait() here returns LuaTuple<[character: Model]>, // so we need to use `[0]` to grab the first (and only) element. const character = Players.LocalPlayer.Character || Players.LocalPlayer.CharacterAdded.Wait()[0]; ``` -------------------------------- ### Luau Module with Static Fields Source: https://roblox-ts.com/docs/guides/using-existing-luau Example of a Luau script returning a table with static fields/functions. ```luau local MyConstants = {} MyConstants.Foo = "Bar" MyConstants.Secret = "hunter2" return MyConstants ``` -------------------------------- ### Using Custom Classes Source: https://roblox-ts.com/docs/guides/using-existing-luau Example of using a custom class modeled in TypeScript. ```typescript print(MyClass.staticProperty); print(MyClass.staticMethod()); const myClass = new MyClass(); print(myClass.instanceProperty); print(myClass.instanceMethod()); ``` -------------------------------- ### Basic Workspace Child Declaration Source: https://roblox-ts.com/docs/guides/indexing-children This example shows how to declare a 'Zombie' child within the 'Workspace' interface in a `services.d.ts` file. ```typescript interface Workspace extends Instance { Zombie: Model; } ``` ```typescript // some other file import { Workspace } from "@rbxts/services"; print(Workspace.Zombie); ``` -------------------------------- ### Default project.json structure for roblox-ts Source: https://roblox-ts.com/docs/guides/syncing-with-rojo This is a truncated example of a default project.json file used by roblox-ts to organize compiled Luau files within Roblox Studio. ```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" } } } } } ``` -------------------------------- ### Instances Type Unions Source: https://roblox-ts.com/docs/api/roblox-api Getting unions of all instance names and types. ```typescript type AllInstanceNames = keyof Instances; type AllInstances = Instances[keyof Instances]; ``` -------------------------------- ### npm publish error output Source: https://roblox-ts.com/docs/faq/publish-not-found Example of the error message encountered when publishing a package for the first time. ```bash 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. ``` -------------------------------- ### identity() Example Source: https://roblox-ts.com/docs/api/functions Demonstrates the identity macro, which compiles to the inner value and is useful for zero-cost type constraint abstraction. ```typescript interface MyInterface { a: number; b: string; c: boolean; } const objects = { abc: identity({ a: 123, b: "abc", c: true, }), }; ``` -------------------------------- ### Usage with Generics Source: https://roblox-ts.com/docs/api/roblox-api Example of using utility interfaces with generic functions for type-safe instance retrieval. ```typescript 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"); ``` -------------------------------- ### AbstractInstances Type Unions Source: https://roblox-ts.com/docs/api/roblox-api Getting unions of all abstract instance names and types. ```typescript type AllAbstractInstanceNames = keyof AbstractInstances; type AllAbstractInstances = AbstractInstances[keyof AbstractInstances]; ``` -------------------------------- ### Problematic Luau code Source: https://roblox-ts.com/docs/guides/lua-tuple An example of Luau code with multiple return values that needs to be typed. ```lua local function foo() return "abc", 123 end ``` -------------------------------- ### Using $tuple macro for multiple returns Source: https://roblox-ts.com/docs/guides/lua-tuple Example of using the $tuple macro to define a function that returns multiple values. ```typescript function hasMultipleReturns() { // this will compile into `return "abc", 123` return $tuple("abc", 123); } ``` -------------------------------- ### npm error message Source: https://roblox-ts.com/docs/faq/publish-as-public Example of the npm error message encountered when publishing a private package. ```bash npm error code E402 npm error 402 Payment Required - PUT https://registry.npmjs.org/@rbxts%2fpackage - You must sign up for private packages ``` -------------------------------- ### CreatableInstances Type Unions Source: https://roblox-ts.com/docs/api/roblox-api Getting unions of all creatable instance names and types. ```typescript type AllCreatableInstanceNames = keyof CreatableInstances; type AllCreatableInstances = CreatableInstances[keyof CreatableInstances]; ``` -------------------------------- ### Generated ReplicatedStorage Typings Source: https://roblox-ts.com/docs/guides/indexing-children An example of typings generated by the 'rbxts-object-to-tree' plugin for 'ReplicatedStorage', showing complex nested structures. ```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; }; } ``` -------------------------------- ### Extending JSX Elements Source: https://roblox-ts.com/docs/guides/roact-jsx Provides an example of extending the global JSX namespace to support custom instances like ProximityPrompt and Folder. ```typescript declare global { namespace JSX { interface IntrinsicElements { // Your instances into here proximityprompt: JSX.IntrinsicElement; folder: JSX.IntrinsicElement; } } } ``` -------------------------------- ### Destructuring multiple returns Source: https://roblox-ts.com/docs/guides/lua-tuple Example of immediately destructuring the result of a function with multiple returns. ```typescript const [actualTimeYielded, totalTime] = wait(1); ``` -------------------------------- ### Assigning multiple returns to a variable Source: https://roblox-ts.com/docs/guides/lua-tuple Example of assigning the result of a function with multiple returns to a variable and then accessing elements by index. ```typescript const result = wait(1); const actualTimeYielded = result[0]; const totalTime = result[1]; ``` -------------------------------- ### ExcludeNominalMembers Source: https://roblox-ts.com/docs/api/utility-types Returns a new object type of all the keys of T which do not start with `_nominal_` ```typescript type ExcludeNominalMembers = Pick>; ``` -------------------------------- ### Nested Child Declaration Source: https://roblox-ts.com/docs/guides/indexing-children This example demonstrates how to declare nested children, like 'Humanoid' inside 'Zombie', using intersection types. ```typescript interface Workspace extends Instance { Zombie: Model & { Humanoid: Humanoid; }; } ``` ```typescript // some other file import { Workspace } from "@rbxts/services"; print(Workspace.Zombie.Humanoid); ``` -------------------------------- ### classIs() Example Source: https://roblox-ts.com/docs/api/functions Illustrates the use of classIs for checking instance types, which compiles to value.ClassName == "ClassName" and is useful for avoiding issues with instance.IsA() for subclasses. ```typescript function foo(value: Instance) { // value.IsA("Script") would return true for LocalScripts! if (classIs(value, "Script")) { print(value.Name); } } ``` -------------------------------- ### typeIs() Example Source: https://roblox-ts.com/docs/api/functions Shows how typeIs helps TypeScript infer that a value has been type-checked, unlike the standard typeOf function. ```typescript function foo(value: unknown) { if (typeIs(value, "Vector3")) { print(value.X); // success! } } ``` -------------------------------- ### assert() Example Source: https://roblox-ts.com/docs/api/functions Demonstrates the usage of the assert function, which uses JavaScript truthiness for its condition. This means that empty strings, 0, and NaN values will cause the assertion to fail in addition to undefined and false. ```typescript function foo(instance: Instance) { assert(instance.IsA("Part")); print(instance.Size); // instance _must_ be a Part to reach this line } ``` -------------------------------- ### Compiling with a custom project.json Source: https://roblox-ts.com/docs/guides/syncing-with-rojo This command shows how to use a different project.json file than the default for compiling. ```bash rbxtsc --rojo other.project.json ``` -------------------------------- ### Adding scripts to StarterPlayer.StarterCharacterScripts Source: https://roblox-ts.com/docs/guides/syncing-with-rojo This JSON snippet shows how to modify the default project.json to include scripts in StarterPlayer.StarterCharacterScripts. ```json "StarterPlayer": { "$className": "StarterPlayer", "StarterPlayerScripts": { "$className": "StarterPlayerScripts", "TS": { "$path": "out/client" } }, "StarterCharacterScripts": { "$className": "StarterCharacterScripts", "TS": { "$path": "out/character" } } } ``` -------------------------------- ### Create a new package Source: https://roblox-ts.com/docs/guides/typescript-packages Command to generate a new package scaffolding. ```bash npm init roblox-ts package ``` -------------------------------- ### Fragments with Shorthand Source: https://roblox-ts.com/docs/guides/roact-jsx Demonstrates the shorthand syntax for creating Fragments in Roact JSX. ```typescript import Roact from "@rbxts/roact"; const fragment = <>; ``` -------------------------------- ### Importing Static Fields Source: https://roblox-ts.com/docs/guides/using-existing-luau How to import and use static fields from a modeled Luau module in TypeScript. ```typescript import { Foo, Secret } from "./MyConstants"; print(Foo, Secret); ``` -------------------------------- ### JSX vs Normal Roact Source: https://roblox-ts.com/docs/guides/roact-jsx Compares the JSX shorthand syntax with the normal Roact.createElement syntax for creating a UI element. ```typescript import Roact from "@rbxts/roact"; const element = ( ); ``` ```typescript 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), }), } ); ``` -------------------------------- ### Pick Source: https://roblox-ts.com/docs/api/utility-types From T pick a set of properties K ```typescript type Pick = { [P in K]: T[P] }; ``` -------------------------------- ### Fragments with Roact.Fragment Source: https://roblox-ts.com/docs/guides/roact-jsx Shows how to create a Fragment using the explicit Roact.Fragment tag. ```typescript import Roact from "@rbxts/roact"; const fragment = ; ``` -------------------------------- ### Importing a Modeled Module Source: https://roblox-ts.com/docs/guides/using-existing-luau How to import and use a modeled Luau module in TypeScript. ```typescript import Module from "./Module"; print(Module); ``` -------------------------------- ### Macro Methods for Math Operators Source: https://roblox-ts.com/docs/guides/datatype-math Demonstrates the use of macro methods `.add()`, `.sub()`, `.mul()`, and `.div()` in roblox-ts to simulate operator overloading for DataType classes. ```typescript a.add(b) compiles to a + b a.sub(b) compiles to a - b a.mul(b) compiles to a * b a.div(b) compiles to a / b ``` -------------------------------- ### rbxtsc CLI Help Source: https://roblox-ts.com/docs/usage Displays help information for the roblox-ts command line interface, including available commands and options. ```bash 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] ``` -------------------------------- ### Key Attribute in Luau vs JSX Source: https://roblox-ts.com/docs/guides/roact-jsx Illustrates the equivalence of the 'Key' attribute in JSX and the child key in Luau Roact. ```lua Roact.createElement("Frame", { Child = Roact.createElement("Frame", {}), }) ``` ```typescript import Roact from "@rbxts/roact"; const element = ( ); ``` -------------------------------- ### npm publish CLI flag Source: https://roblox-ts.com/docs/faq/publish-as-public Command to publish a package with public access using the npm CLI. ```bash npm publish --access public ``` -------------------------------- ### Custom Components with JSX Source: https://roblox-ts.com/docs/guides/roact-jsx Demonstrates using custom components defined with PascalCase as tag names in JSX. ```typescript import Roact from "@rbxts/roact"; interface MyComponentProps { value: string; } function MyComponent(props: MyComponentProps) { return ; } const element = ; ``` -------------------------------- ### package.json publishConfig setting Source: https://roblox-ts.com/docs/faq/publish-as-public Configuration to set the package access to public in package.json. ```json { "name": "@rbxts/package", "version": "1.0.0", "publishConfig": { "access": "public" } // other fields } ``` -------------------------------- ### Spreading into Attributes Source: https://roblox-ts.com/docs/guides/roact-jsx Shows how to spread an object into attributes using the {...exp} syntax for reusable property sets. ```typescript import Roact from "@rbxts/roact"; const MyStyle: Partial> = { BackgroundColor3: new Color3(0, 0, 0), BackgroundTransparency: 0.5, }; const element = ; ``` -------------------------------- ### Typings for Custom Classes Source: https://roblox-ts.com/docs/guides/using-existing-luau TypeScript type definitions for modeling custom OOP classes in Luau. ```typescript interface MyClass { instanceProperty: string; instanceMethod(): number; } interface MyClassConstructor { new (): MyClass; staticProperty: string; staticMethod(): number; } declare const MyClass: MyClassConstructor; export = MyClass; ``` -------------------------------- ### Key Attribute with Fragment Source: https://roblox-ts.com/docs/guides/roact-jsx Demonstrates how a Key attribute on a top-level element implicitly wraps it in a Roact.Fragment. ```typescript import Roact from "@rbxts/roact"; const element = ; ``` -------------------------------- ### InstanceMethods Source: https://roblox-ts.com/docs/api/utility-types Given an Instance T, returns an object with only methods. ```typescript type InstanceMethods = Pick>; ``` -------------------------------- ### Spreading into Children Source: https://roblox-ts.com/docs/guides/roact-jsx Demonstrates spreading an array into children using the {...exp} syntax for dynamic lists of elements. ```typescript import Roact from "@rbxts/roact"; const listItems = new Array(); for (let i = 0; i < 10; i++) { listItems.push(); } const element = {...listItems}; ``` -------------------------------- ### _ Source: https://roblox-ts.com/docs/api/utility-types Placeholder that sometimes helps force TS to display what you want it to. ```typescript type _ = T; ``` -------------------------------- ### Ref Attribute Source: https://roblox-ts.com/docs/guides/roact-jsx Shows how to use the Ref attribute in JSX, which maps to the [Roact.Ref] key in Luau. ```typescript import Roact from "@rbxts/roact"; const ref = Roact.createRef(); const element = ; ``` -------------------------------- ### InstanceMethodNames Source: https://roblox-ts.com/docs/api/utility-types Given an Instance T, returns a unioned type of all method names. ```typescript type InstanceMethodNames = ExtractKeys; ``` -------------------------------- ### Partial Source: https://roblox-ts.com/docs/api/utility-types Make all properties in T optional ```typescript type Partial = { [P in keyof T]?: T[P] }; ``` -------------------------------- ### Record Source: https://roblox-ts.com/docs/api/utility-types Construct a type with a set of properties K of type T ```typescript type Record = { [P in K]: T }; ``` -------------------------------- ### Provided Types Source: https://roblox-ts.com/docs/api/roblox-api Every Roblox class (`Instance`, `Part`, `Humanoid`, `Workspace`, etc.) is provided as a global/ambient type. You can use these types to describe variables, function parameters, function return types, and just about anything else in your code. ```typescript // note: The type Part could be inferred here if not provided const part: Part = new Instance("Part"); print(part.Size); ``` ```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")); ``` -------------------------------- ### TypeScript Types for Static Fields Source: https://roblox-ts.com/docs/guides/using-existing-luau TypeScript type declarations for a Luau module returning static fields. ```typescript export declare const Foo: string; export declare const Secret: string; ``` -------------------------------- ### InstanceProperties Source: https://roblox-ts.com/docs/api/utility-types Given an Instance T, returns an object with only properties. ```typescript type InstanceProperties = Pick>; ``` -------------------------------- ### Instances Interface Source: https://roblox-ts.com/docs/api/roblox-api An interface mapping string names to types for all Roblox instances, inheriting from Services, CreatableInstances, and AbstractInstances. ```typescript interface Instances extends Services, CreatableInstances, AbstractInstances { AnimationTrack: AnimationTrack; BaseWrap: BaseWrap; CatalogPages: CatalogPages; DataModel: DataModel; // ... many more instances! } ``` -------------------------------- ### Using Values as Children Source: https://roblox-ts.com/docs/guides/roact-jsx Demonstrates how to use conditional values (booleans and undefined) as children in Roact JSX. ```typescript import Roact from "@rbxts/roact"; let condition = false; const element = ( {condition && } {condition ? : undefined} ); ``` -------------------------------- ### Constructors Source: https://roblox-ts.com/docs/api/roblox-api `.new()` functions (like `Vector3.new()` or `CFrame.new()`) should instead be called with the `new` operator. `new T(...)` will always compile to `T.new(...)`. ```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); ``` -------------------------------- ### InstanceEvents Source: https://roblox-ts.com/docs/api/utility-types Given an Instance T, returns an object with only events. ```typescript type InstanceEvents = Pick>; ``` -------------------------------- ### Property Access for Components Source: https://roblox-ts.com/docs/guides/roact-jsx Shows how to use components nested within objects or namespaces as tag names in JSX. ```typescript import Roact from "@rbxts/roact"; interface MyComponentProps { value: string; } function MyComponent(props: MyComponentProps) { return ; } const Components = { MyComponent: MyComponent, }; const element = ; ``` -------------------------------- ### InstanceEventNames Source: https://roblox-ts.com/docs/api/utility-types Given an Instance T, returns a unioned type of all event names. ```typescript type InstanceEventNames = ExtractKeys; ``` -------------------------------- ### ConstructorParameters Source: https://roblox-ts.com/docs/api/utility-types Obtain the parameters of a constructor function type in a `tuple | never` ```typescript type ConstructorParameters any> = T extends new (...args: infer P) => any ? P : never; ``` -------------------------------- ### InstancePropertyNames Source: https://roblox-ts.com/docs/api/utility-types Given an Instance `T`, returns a unioned type of all property names. ```typescript type InstancePropertyNames = ExcludeKeys; ``` -------------------------------- ### CreatableInstances Interface Source: https://roblox-ts.com/docs/api/roblox-api An interface mapping string names to types for instances creatable with Instance.new(). ```typescript interface CreatableInstances { Accessory: Accessory; Accoutrement: Accoutrement; Actor: Actor; AlignOrientation: AlignOrientation; // ... many more instances! } ``` -------------------------------- ### Enable PowerShell Script Execution Source: https://roblox-ts.com/docs/faq/powershell This command allows PowerShell to run scripts downloaded from the internet, which is necessary for roblox-ts. ```powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser ``` -------------------------------- ### Required Source: https://roblox-ts.com/docs/api/utility-types Make all properties in T required ```typescript type Required = { [P in keyof T]-?: T[P] }; ``` -------------------------------- ### Services Source: https://roblox-ts.com/docs/api/roblox-api `Services` is an interface consisting of a mapping of string name to type for every Roblox service which you can fetch with `game:GetService("ServiceName")`. ```typescript interface Services { AnalyticsService: AnalyticsService; AppUpdateService: AppUpdateService; AssetCounterService: AssetCounterService; AssetDeliveryProxy: AssetDeliveryProxy; // ... many more services! } ``` ```typescript type AllServiceNames = keyof Services; type AllServices = Services[keyof Services]; ``` -------------------------------- ### Readonly Source: https://roblox-ts.com/docs/api/utility-types Make all properties in T readonly ```typescript type Readonly = { readonly [P in keyof T]: T[P] }; ``` -------------------------------- ### Exceptions Source: https://roblox-ts.com/docs/api/roblox-api Deprecated types are usually not provided. Exceptions to this rule are made for API members which do not have a non-deprecated functional equivalent. One notable exception: `Instance.Changed` is not provided as it conflicts with inheritance. Usually, you want to use `Instance.GetPropertyChangedSignal()` instead. ```typescript import { Workspace } from "@rbxts/services"; Workspace.GetPropertyChangedSignal("DistributedGameTime").Connect(() => { print(Workspace.DistributedGameTime); }); ``` ```typescript function foo(part: Part) { (part as Part & ChangedSignal).Changed.Connect(name => {}) } ``` -------------------------------- ### InstanceType Source: https://roblox-ts.com/docs/api/utility-types Obtain the return type of a constructor function type ```typescript type InstanceType) => any> = T extends new (...args: Array) => infer R ? R : any; ``` -------------------------------- ### AbstractInstances Interface Source: https://roblox-ts.com/docs/api/roblox-api An interface mapping string names to types for instances that will never be created, useful for inheritance checks. ```typescript interface AbstractInstances { BackpackItem: BackpackItem; BasePart: BasePart; BasePlayerGui: BasePlayerGui; BaseScript: BaseScript; // ... many more instances! } ``` -------------------------------- ### TypeScript Type Declaration for Module Return Value Source: https://roblox-ts.com/docs/guides/using-existing-luau TypeScript type declaration to model a Luau module's return value using an export assignment. ```typescript interface Module { // define Module member types } // create a value from our type declare const Module: Module; export = Module; ``` -------------------------------- ### Change Attribute Source: https://roblox-ts.com/docs/guides/roact-jsx Demonstrates the 'Change' attribute for handling property changes on UI instances in JSX. Note the double curly braces. ```typescript import Roact from "@rbxts/roact"; const element = ( print(`${rbx.GetFullName()} changed Position!`), }} /> ); ``` -------------------------------- ### Incorrect TypeScript tuple typing Source: https://roblox-ts.com/docs/guides/lua-tuple An attempt to type the Luau multiple return using TypeScript tuples, which is incorrect because TypeScript tuples are arrays. ```typescript declare function foo(): [string, number]; ``` -------------------------------- ### Extract Source: https://roblox-ts.com/docs/api/utility-types Extract from T those types that are assignable to U ```typescript type Extract = T extends U ? T : never; ``` -------------------------------- ### ExtractKeys Source: https://roblox-ts.com/docs/api/utility-types Returns a union of all the keys of T whose values extend from U ```typescript type ExtractKeys = { [K in keyof T]: T[K] extends U ? K : never }[keyof T]; ``` -------------------------------- ### Method declarations are considered methods. Source: https://roblox-ts.com/docs/guides/callbacks-vs-methods Illustrates that a method declaration within an object is treated as a method. ```typescript const obj = { foo(bar: number) {} } obj.foo(123); // obj:foo(123) ``` -------------------------------- ### WritableInstanceProperties Source: https://roblox-ts.com/docs/api/utility-types Given an Instance T, returns an object with readonly fields, methods, and events filtered out. ```typescript type WritableInstanceProperties = WritableProperties>; ``` -------------------------------- ### Event Attribute Source: https://roblox-ts.com/docs/guides/roact-jsx Illustrates the 'Event' attribute for connecting event listeners in JSX. Note the double curly braces. ```typescript import Roact from "@rbxts/roact"; const element = ( print(`${rbx.GetFullName()} was clicked at (${x}, ${y})`), }} /> ); ``` -------------------------------- ### Parameters Source: https://roblox-ts.com/docs/api/utility-types Obtain the parameters of a function type in a `tuple | never`. ```typescript type Parameters any> = T extends (...args: infer P) => any ? P : never; ``` -------------------------------- ### RemoteEvent Types Source: https://roblox-ts.com/docs/api/roblox-api New roblox-ts users are usually confused why `RemoteEvent.OnServerEvent` only allows `unknown` arguments. ```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) => {}); ``` ```typescript const remoteEvent = new Instance("RemoteEvent"); remoteEvent.OnServerEvent.Connect((player: Player, points: unknown) => { if (!typeIs(points, "number")) { return; } // do something with points }); ``` -------------------------------- ### NonNullable Source: https://roblox-ts.com/docs/api/utility-types Exclude null and undefined from T ```typescript type NonNullable = unknown extends T ? defined : T extends null | undefined ? never : T; ``` -------------------------------- ### Omit Source: https://roblox-ts.com/docs/api/utility-types Returns a subset of type T which excludes properties K ```typescript type Omit = Pick>; ``` -------------------------------- ### ExcludeKeys Source: https://roblox-ts.com/docs/api/utility-types Returns a union of all the keys of T whose values do not extend from U ```typescript type ExcludeKeys = { [K in keyof T]: T[K] extends U ? never : K }[keyof T]; ``` -------------------------------- ### Functions with `this: void` are always callbacks. Source: https://roblox-ts.com/docs/guides/callbacks-vs-methods Demonstrates that a function with a `this: void` parameter is always compiled as a callback. ```typescript const obj = { foo(this: void, bar: number) {} } obj.foo(123); // obj.foo(123) ``` -------------------------------- ### Functions with `this` typed as anything except `void` are always methods. Source: https://roblox-ts.com/docs/guides/callbacks-vs-methods Shows that a function with a `this` parameter typed as anything other than `void` is always compiled as a method. ```typescript declare const obj: { foo: (this: typeof obj, bar: number) => void; } obj.foo(123); // obj:foo(123) ``` -------------------------------- ### Globals Source: https://roblox-ts.com/docs/api/roblox-api All global values from the Roblox API are present in roblox-ts typings. ```typescript print("Hello World!"); ``` ```typescript const zero = math.sin(math.pi); ``` ```typescript coroutine.wrap(() => { print("A"); wait(1); print("B"); })(); ``` -------------------------------- ### Function declarations are considered callbacks. Source: https://roblox-ts.com/docs/guides/callbacks-vs-methods Demonstrates that a standard function declaration within an object is treated as a callback. ```typescript function foo(bar: number) {} const obj = { foo: foo }; obj.foo(123); // obj.foo(123) ``` -------------------------------- ### ReturnType Source: https://roblox-ts.com/docs/api/utility-types Obtain the return type of a function type ```typescript type ReturnType) => any> = T extends (...args: Array) => infer R ? R : any; ``` -------------------------------- ### Reconstruct Source: https://roblox-ts.com/docs/api/utility-types Combines a series of intersections into one object, e.g. { x: number } & { y: number } becomes { x: number, y: number } ```typescript type Reconstruct = _<{ [K in keyof T]: T[K] }>; ``` -------------------------------- ### LuaTuple type definition Source: https://roblox-ts.com/docs/guides/lua-tuple The definition of the LuaTuple type in roblox-ts. ```typescript type LuaTuple> = T & { readonly LUA_TUPLE: never }; ``` -------------------------------- ### Writable Source: https://roblox-ts.com/docs/api/utility-types Make all properties in T non-readonly. ```typescript type Writable = { -readonly [P in keyof T]: T[P] }; ``` -------------------------------- ### UnionToIntersection Source: https://roblox-ts.com/docs/api/utility-types Converts a series of object unions to a series of intersections, e.g. A | B becomes A & B ```typescript type UnionToIntersection = (T extends object ? (k: T) => void : never) extends (k: infer U) => void ? U : never; ``` -------------------------------- ### Exclude Source: https://roblox-ts.com/docs/api/utility-types Exclude from T those types that are assignable to U ```typescript type Exclude = T extends U ? never : T; ``` -------------------------------- ### ExtractMembers Source: https://roblox-ts.com/docs/api/utility-types Returns a new object type of all the keys of T whose values extend from U ```typescript type ExtractMembers = Pick>; ``` -------------------------------- ### Function expressions inside of object literals are considered methods. Source: https://roblox-ts.com/docs/guides/callbacks-vs-methods Explains that a function expression assigned to an object property is treated as a method. ```typescript const obj = { foo: function (bar: number) {} } obj.foo(123); // obj:foo(123) ``` -------------------------------- ### WritablePropertyNames Source: https://roblox-ts.com/docs/api/utility-types Given an object `T`, returns a unioned type of all non-readonly property names. ```typescript type WritablePropertyNames = { [K in keyof T]-?: T[K] extends Callback ? never : (() => F extends { [Q in K]: T[K] } ? 1 : 2) extends () => F extends { -readonly [Q in K]: T[K]; } ? 1 : 2 ? K : never; }[keyof T]; ``` -------------------------------- ### WritableProperties Source: https://roblox-ts.com/docs/api/utility-types Given an object `T`, returns an object with readonly fields filtered out. ```typescript type WritableProperties = Pick>; ``` -------------------------------- ### ExcludeMembers Source: https://roblox-ts.com/docs/api/utility-types Returns a new object type of all the keys of T whose values do not extend from U ```typescript type ExcludeMembers = Pick>; ``` -------------------------------- ### Arrow function expressions are considered callbacks. Source: https://roblox-ts.com/docs/guides/callbacks-vs-methods Shows that an arrow function expression assigned to an object property is treated as a callback. ```typescript const obj = { foo: (bar: number) => {} } obj.foo(123); // obj.foo(123) ``` -------------------------------- ### ThisParameterType Source: https://roblox-ts.com/docs/api/utility-types Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter. ```typescript type ThisParameterType = T extends (this: infer U, ...args: Array) => any ? U : unknown; ``` -------------------------------- ### OmitThisParameter Source: https://roblox-ts.com/docs/api/utility-types Removes the 'this' parameter from a function type. ```typescript type OmitThisParameter = unknown extends ThisParameterType ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.