Lesson 6 of 6

Types: strict mode, the new type solver, generics

Learn Luau's type system for Roblox. Strict mode, annotations, singleton unions, unknown and refinement, typeof, generics, type packs, the new type solver's general release and luau-lsp analyze in CI, with Beacon Yard's Types.luau.

Tool lesson, about 75 minutes, 12 steps

By the end you can

  • Read and write type annotations, aliases and singleton unions such as Beacon Yard's RoundPhase
  • Narrow an unknown value from outside into a known type, and say why the narrowing has to run at run time
  • Write a generic function and read a type pack at an intro level
  • Run the type checker outside Studio with luau-lsp analyze, and say where the new type solver stands

Before this: Objects in Luau: metatables, classes, composition

1Do not trust values from outside

When the server and a client send messages to each other (which Module 3 covers), the receiving side cannot trust what arrived. Later in Beacon Yard, the client receives a round phase name as unknown and checks it one exact string at a time before using it:

local function parsePhase(value: unknown): RoundPhase?
	if value == "Idle" then
		return "Idle"
	elseif value == "Active" then
		return "Active"
	elseif value == "Cooldown" then
		return "Cooldown"
	end
	return nil
Figure 1.1

Read the first line slowly. It takes unknown and returns RoundPhase?: a valid phase, or nil. Everything in this lesson is a way of writing, checking or relying on lines like that.

Roblox Studio
Studio's script editor showing src/shared/Types.luau: the strict comment, export type RoundPhase, Profile, ShopItem and FeedbackKind, and return {} at the end.

Select a numbered pin, or a row below, to read what it marks.

Figure 1.2.

Beacon Yard's Types.luau, the shared names for data passed between server and client.

Types.luau ends with return {}. What does a script get at run time when it requires Types?

  1. An empty table; the type names exist only for the checker
  2. A table with RoundPhase, Profile, ShopItem and FeedbackKind as fields
  3. An error, because a module must return functions
  4. The string "Types"
Answer

An empty table; the type names exist only for the checker. The module returns an empty table. export type lines are read by the type checker and erased before the code runs, so Types.RoundPhase in an annotation works while the required table stays empty.

Open this step in lesson mode · Link to this step · This confused me

2Three modes, one project setting

Luau's type checker works in three modes, including strict modeStrict modeThe Luau type-checking mode that infers a type for everything and reports anything that does not fit.Think of it as an inspector who reads every jar label before the kitchen opens., set by a comment on the first line of a file1:

  • --!nocheck turns checking off for the file.
  • --!nonstrict reports only things that are certainly wrong. It is the default for a script with no comment, which comes from the Workspace.LuauTypeCheckMode property (Roblox's templates set it to Nonstrict).
  • --!strict infers a type for everything and reports anything that does not fit.

Beacon Yard uses strict everywhere: every file starts with --!strict, and the project's .luaurc sets "languageMode": "strict" so editors treat new files the same way.

Both sidesRemember: Type annotations is labels on jars.

In a --!strict file, which of these does the checker report before you press Play?

  1. Passing "25" (a string) to a parameter annotated number
  2. Assigning "Running" to a variable of type RoundPhase
  3. Reading a field Config does not have, such as Config.COIN_VALEU
  4. A client sending "Nope" to a server handler at run time
Answer

Passing "25" (a string) to a parameter annotated number; Assigning "Running" to a variable of type RoundPhase; Reading a field Config does not have, such as Config.COIN_VALEU. The first three are mistakes in the source, so strict mode reports them. What a client sends arrives while the game runs, after checking is over, so only runtime code can catch it.

Open this step in lesson mode · Link to this step · This confused me

3Writing types

Annotations go after a colon. The common shapes:

  • primitives: number, string, boolean, and nil
  • optional: Player? means a Player or nil
  • lists: { BasePart }; dictionaries: { [Player]: number }
  • table shapes: { coins: number, speedOwned: boolean }
  • functions: (player: Player, amount: number) -> boolean
  • unions: string | number, and singletons such as "Idle" | "Active"

type Name = ... gives a type a name, and export type makes it usable from other files as Types.Name. Annotations do nothing at run time, so the cell below runs exactly as it would without them.

Luau
type Profile = { coins: number, speedOwned: boolean }
type ShopItem = "Speed" | "Shield" | "CoinPack"
local PRICES: { [ShopItem]: number } = { Speed = 25, Shield = 40, CoinPack = 0 }
local function trySpend(profile: Profile, item: ShopItem): boolean
	local price = PRICES[item]
	if profile.coins < price then
		return false
	end
	profile.coins -= price
	return true
end
local profile: Profile = { coins = 30, speedOwned = false }
print(trySpend(profile, "Speed"), profile.coins, trySpend(profile, "Shield"))
Figure 3.1. Expected output: true 5 false

Under --!strict, the checker reports an error in this fragment. Which line?

type RoundPhase = "Idle" | "Active" | "Cooldown"
local phase: RoundPhase = "Idle"
local function startDrill()
    phase = "Running"
end
Answer

Line 4: phase = "Running". Fixed: phase = "Active". "Running" is not one of the three singletons, so strict mode rejects the assignment before the game runs.

Open this step in lesson mode · Link to this step · This confused me

4unknown, refinement and casts

unknown means "could be anything, and you must find out before using it". You cannot index it, add to it or pass it on as anything more specific until you check it. Checks narrow the type inside their branch; this is called refinementType refinementNarrowing a value's type inside a branch by checking it, for example with typeof or ==.Think of it as opening the jar and looking before you trust the label.. typeof(x) == "number", x == "Idle", x ~= nil and x:IsA("BasePart") all refine.

:: is a cast: value :: number tells the checker "trust me". It changes nothing at run time. Casting a trusted internal module is fine, whereas casting untrusted input from a client hides the exact bug strict mode is there to catch.

Luau
type RoundPhase = "Idle" | "Active" | "Cooldown"
local function parsePhase(value: unknown): RoundPhase?
	if value == "Idle" then
		return "Idle"
	elseif value == "Active" then
		return "Active"
	elseif value == "Cooldown" then
		return "Cooldown"
	end
	return nil
end
print(parsePhase("Active"), parsePhase("Running"), parsePhase(42))
local function safeNumber(value: unknown): number
	if typeof(value) == "number" and value == value then
		return value
	end
	return 0
end
print(safeNumber(15), safeNumber("15"), safeNumber(0 / 0))
Figure 4.1. Expected output: Active nil nil 15 0 0

A server buy handler is written function(player: Player, item: unknown). What would change if it were item: ShopItem instead?

  1. The checker would let the handler treat item as a ShopItem without checking, but a client could still send anything at run time
  2. Roblox would reject bad strings before they reach the server
  3. Nothing at all; unknown and ShopItem are the same
  4. The game would stop compiling
Answer

The checker would let the handler treat item as a ShopItem without checking, but a client could still send anything at run time. Nobody does. Labelling the parameter ShopItem only silences the checker. unknown forces the code to compare with "Speed", "Shield" and "CoinPack", which is the check that actually stops a forged request.

Open this step in lesson mode · Link to this step · This confused me

5typeof in a type

Sometimes the easiest way to name a type is to point at a value. In a type position, typeof(expr) means "the type the checker inferred for this expression". Two places you will see it:

  • type ConfigShape = typeof(Config) gives every field of a config table its inferred type, so you never write the list twice.
  • type Drone = typeof(setmetatable({} :: { health: number }, Drone)) names the type of a class's objects, as in the objects lesson.

Do not confuse it with the runtime function typeof(value), which returns a string such as "Vector3" while the game runs. Same word, two jobs: one for the checker, one for running code.

Luau with roblox-lite (not Roblox)
local Config = { COIN_VALUE = 5, SPEED_PRICE = 25 }
type ConfigShape = typeof(Config)
local copy: ConfigShape = table.clone(Config)
print(typeof(copy.COIN_VALUE), typeof(Vector3.new(0, 2.2, 0)), typeof(copy))
Figure 5.1. Expected output: number Vector3 table

Open this step in lesson mode · Link to this step · This confused me

6Generics: one function, many types

Some functions do not care what they hold. "Return the first item that matches" works the same for a list of prices and a list of pads. A genericGenericA type or function with a placeholder type, written in angle brackets, that is filled in where it is used.Think of it as a box with a label that says 'the same kind of thing that went in'. function names a placeholder type in angle brackets, and the checker fills it in at each call2:

function firstWhere<T>(list: { T }, predicate: (T) -> boolean): T?

Called with a { number }, T is number and the result is number?. Called with { BasePart }, the result is BasePart?, and the editor knows it has a .Position. Generic types work the same way: type Pool<T> = { items: { T }, free: { T } }.

Luau
local function firstWhere<T>(list: { T }, predicate: (T) -> boolean): T?
	for _, item in list do
		if predicate(item) then
			return item
		end
	end
	return nil
end
print(firstWhere({ 40, 25, 0 }, function(price)
	return price < 30
end))
local pad = firstWhere({ { name = "Pad1", index = 1 }, { name = "Pad2", index = 2 } }, function(p)
	return p.index == 2
end)
print(pad and pad.name)
Figure 6.1. Expected output: 25 Pad2

firstWhere<T>(list: { T }, predicate: (T) -> boolean): T? is called with a list of type { Player }. What type does the checker give the result?

  1. Player?
  2. T?
  3. { Player }
  4. unknown
Answer

Player?. The list is { Player }, so T is Player and the return type T? becomes Player?: a player, or nil when nothing matched.

Open this step in lesson mode · Link to this step · This confused me

7Type packs, at an intro level

Luau functions can take and return several values, so the type system has a name for "several types in a row": a type pack. Two patterns you will meet in Beacon Yard:

  • ...: MessageArg types every extra variadic argument as a MessageArg.
  • (Profile, boolean) as a return type means "returns a profile and a boolean flag".

Generic packs use three dots after the name: <A...>. A signal type might be type Signal<A...> = { Fire: (self: Signal<A...>, A...) -> () }, so Signal<Player, number> fires with exactly a player and a number. You will mostly read packs in library code rather than write them.

type RemoteArg = string | number | boolean | Vector3 | nil
Figure 7.1

Given fireAll(name: string, ...: RemoteArg) where RemoteArg is string | number | boolean | Vector3 | nil, which calls does the checker accept?

  1. fireAll("RoundState", "Active", 1234.5)
  2. fireAll("Feedback", "coin", "+5")
  3. fireAll("Feedback", { coins = 5 })
  4. fireAll("RoundState")
Answer

fireAll("RoundState", "Active", 1234.5); fireAll("Feedback", "coin", "+5"); fireAll("RoundState"). Strings and numbers are RemoteArgs, and zero extra arguments is fine for a variadic. A table is not a RemoteArg, so the third call is rejected.

Open this step in lesson mode · Link to this step · This confused me

8The new type solver

The checker itself was rebuilt. Luau's new type solver gives better inference, fewer false errors, read-only table properties and type functions. Roblox announced its general release on the DevForum on 20 November 20253. That post says:

  • It is on by default for nocheck and nonstrict scripts in Studio.
  • Strict-mode Studio places opt in by setting Workspace.UseNewLuauTypeSolver to Enabled.

The post says nothing about luau-lsp, the command-line checker you meet below. Its own changelog lists "analyze uses the new solver by default" as unreleased, after 1.70.1. That is the version rokit.toml pins and the newest release at the time of writing, so a pinned analyze still uses the old solver. When a release ships the change, --flag:LuauSolverV2=false keeps the old one.

According to the general-release post, what must a strict-mode Studio place like Beacon Yard set to use the new solver?

  1. Set Workspace.UseNewLuauTypeSolver to Enabled
  2. Nothing; strict files got it automatically in Studio
  3. Remove --!strict from every file
  4. Install a plugin
Answer

Set Workspace.UseNewLuauTypeSolver to Enabled. nocheck and nonstrict scripts got the new solver by default in Studio. Strict-mode places opt in with Workspace.UseNewLuauTypeSolver.

Open this step in lesson mode · Link to this step · This confused me

9Check types outside Studio

Studio checks the file you have open. A team wants every file checked on every change, with no Studio at all. luau-lspluau-lspThe Luau language server: autocomplete, hover docs and type errors in an external editor.Think of it as studio's script editor smarts, inside VS Code., the language server behind the VS Code extension, has a command-line mode for that: luau-lsp analyze4. It reads a Rojo sourcemap to understand where each file lives in the game, and a definitions file to know Roblox's API.

Beacon Yard's m14-ship milestone already wires this into CI: rokit.toml pins luau-lsp@1.70.1, .github/workflows/ci.yml runs a types job, and scripts/typecheck.sh checks src, tests and unit (see Continuous integration: every check, blocking for the full CI pipeline).

rojo sourcemap default.project.json -o sourcemap.json
 
"$lsp" analyze \
	--sourcemap sourcemap.json \
	--definitions="$types" \
	--base-luaurc .luaurc \
	src tests
Figure 9.1

Current luau-lsp recommends naming the definitions file with --definitions:@roblox=... (unnamed --definitions= was deprecated in luau-lsp 1.56.0, though backwards compatibility remains) and downloading from luau-lsp.pages.dev to avoid GitHub rate limits. Beacon Yard's own typecheck.sh still uses the unnamed form and downloads from the pinned release on GitHub, and both work. Run wally install first, because ShopApp and ShopGui require React from Packages/, which only exists after it. Note also that in Windows PowerShell, curl is an alias for Invoke-WebRequest and has no -L flag, so use Invoke-WebRequest or curl.exe.

Windows

powershell
wally install
rojo sourcemap default.project.json -o sourcemap.json
Invoke-WebRequest -Uri "https://luau-lsp.pages.dev/type-definitions/globalTypes.None.d.luau" -OutFile "globalTypes.d.luau"
luau-lsp analyze --platform=roblox --sourcemap=sourcemap.json --definitions:@roblox=globalTypes.d.luau --base-luaurc=.luaurc src tests

macOS

bash
wally install
rojo sourcemap default.project.json -o sourcemap.json
curl -fsSL -o globalTypes.d.luau https://luau-lsp.pages.dev/type-definitions/globalTypes.None.d.luau
luau-lsp analyze --platform=roblox --sourcemap=sourcemap.json --definitions:@roblox=globalTypes.d.luau --base-luaurc=.luaurc src tests

Linux

bash
wally install
rojo sourcemap default.project.json -o sourcemap.json
curl -fsSL -o globalTypes.d.luau https://luau-lsp.pages.dev/type-definitions/globalTypes.None.d.luau
luau-lsp analyze --platform=roblox --sourcemap=sourcemap.json --definitions:@roblox=globalTypes.d.luau --base-luaurc=.luaurc src tests

When a file breaks a type, analyze names the file, its place in the game tree, the line and column, and what is wrong:

Terminal
A PowerShell window after luau-lsp analyze: an error for the client script Hud.luau at line 247, column 2, a TypeError saying the value should be Active, Cooldown or Idle but got Running.

Select a numbered pin, or a row below, to read what it marks.

Figure 9.2.

luau-lsp analyze reporting a string that is not a RoundPhase.

Build along

m14-ship

  • rokit.toml
  • scripts/typecheck.sh
  • .github/workflows/ci.yml
  1. Check out m14-ship (git checkout m14-ship), run rokit install if needed, and verify luau-lsp --version.

    You should see rokit.toml lists luau-lsp and luau-lsp --version prints a version.

  2. Run wally install, then the first two commands for your system above to generate sourcemap.json and download globalTypes.d.luau.

    You should see sourcemap.json and globalTypes.d.luau exist in the repository root (both git-ignored).

  3. Run the luau-lsp analyze command for your system (the pinned 1.70.1 uses the old solver by default; add --flag:LuauSolverV2=true to compare with the new one). Then undo any test edit with git checkout -- ..

    You should see luau-lsp analyze prints no errors and exits with code 0. Temporarily changing a RoundPhase string to Running prints an error with the file and line.

Open this step in lesson mode · Link to this step · This confused me

10Typed Luau, or TypeScript?

Typed code for Roblox

OptionWhat it isWhen pros pick itTrade-offs
Luau strict modeLuau's own checker, in Studio and luau-lsp.The default for most professional Roblox teams, and for Beacon Yard.Some patterns (classes, deep generics) still need casts; strict Studio places opt in to the new solver.
luau-lsp analyze in CIThe same checker from the command line, with Rojo paths.Teams using Rojo who want every change checked before merge.Needs a sourcemap and API definitions kept up to date.
roblox-tsWrite TypeScript; a compiler turns it into Luau.Studios with web developers, or that want TypeScript's tooling and npm packages.A build step, generated code you debug through, and a smaller pool of Roblox examples written in it.
nonstrict everywhereOnly definite errors are reported.Prototypes and game jams.Misses the type mistakes strict mode catches; harder to move to strict later.
Where does it break?“Labels on jars” is a good picture of type annotations. Where does it stop being true?

It breaks here. Labels are checked before the game runs, and only then. While it runs, nothing reads them, so a value that arrives from a client or a DataStore can be anything whatever its label says.

The true model. Annotations feed a static checker that runs on the source code. At run time Luau ignores them. Code that receives outside data marks it unknown and narrows it with typeof, comparisons or type guards before treating it as a specific type.

CI runs luau-lsp analyze and passes. Which bug can still reach players?

  1. A client sending a table instead of a string, if the server handler casts the argument with :: ShopItem instead of checking it
  2. A function called with a string where a number is annotated
  3. A misspelt field on Config
  4. An assignment of "Running" to a RoundPhase
Answer

A client sending a table instead of a string, if the server handler casts the argument with :: ShopItem instead of checking it. The other three are in the source, so analyze catches them. A forged client argument arrives at run time, and a cast tells the checker not to worry about it. Only a runtime check stops it.

Open this step in lesson mode · Link to this step · This confused me

11Challenges

Level 1, Apprentice

Challenge

Read a real signature until you could have written it.

Start from
The game at milestone m06 (download)

Done means

  • You write the full signature of DataService.trySpend from memory
  • You check it against the file and explain each part

Hints

  1. It takes a player and an amount, and answers yes or no.
  2. Open src/server/DataService.luau on m06-drone-wrench and search for trySpend.
Solution
luau
function DataService.trySpend(player: Player, amount: number): boolean
-- player: Player   the engine's Player instance
-- amount: number   the price, a plain number
-- : boolean        true when the coins were spent

Level 2, Builder

Challenge

Write parseKind(value: unknown): FeedbackKind? in the cell below. Passing the tests completes this challenge.

Start from
The Run cell below
Check it here
Run the code cell in the lesson view; the challenge completes when it passes. No Studio needed.

Done means

  • parseKind accepts "coin", "buy" and "deny" and returns the exact literal
  • Wrong case, numbers and nil return nil
  • All five assertions pass

Hints

  1. Compare value == "coin", elseif value == "buy", elseif value == "deny".
  2. Return the string literal in each branch so strict mode narrows the type.
Solution
luau
local function parseKind(value: unknown): FeedbackKind?
	if value == "coin" then
		return "coin"
	elseif value == "buy" then
		return "buy"
	elseif value == "deny" then
		return "deny"
	end
	return nil
end
Luau
type FeedbackKind = "coin" | "buy" | "deny"
-- Return the kind if value is one of the three strings, otherwise nil.
local function parseKind(value: unknown): FeedbackKind?
	return nil
end
Figure 11.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

Level 3, Professional

Challenge

Start from the m14-ship tag in the game repo and write a type-safe parser for shop items and a generic helper. You edit only challenges/luau_types_work.luau; the solution is challenges/solutions/luau-types.md in the game repo.

Start from
The game at milestone m14 (download)
Grade it
In Studio, press Play, then run game.ServerScriptService.RunGameTests:Invoke("luau-types") in the server command bar. Copy the pass code from Output.

Done means

  • challenges/luau_types_work.luau implements parseItem(value: unknown): ShopItem? by comparing, not casting
  • firstWhere<T> returns the first item the predicate accepts, or nil
  • The Course Runner prints TEST PASS for all eleven checks and a pass code
  • luau-lsp analyze reports no errors for the file

Hints

  1. parseItem has the same shape as parsePhase.
  2. firstWhere is the generic cell in this lesson, unchanged.
  3. If analyze complains that unknown is not a ShopItem, you returned value instead of a string literal.

Open this step in lesson mode · Link to this step · This confused me

12Recap

Retiring the analogy

You no longer need “labels on jars”. Annotations feed a static checker that runs on the source code. At run time Luau ignores them. Code that receives outside data marks it unknown and narrows it with typeof, comparisons or type guards before treating it as a specific type.

Recap

  1. --!strict checks every file against its annotations before the game runs. Aliases and singleton unions (RoundPhase, ShopItem) name the data both sides share.
  2. Values from outside are unknown until code narrows them with typeof or comparisons; a :: cast silences the checker without checking anything.
  3. Generics let one function serve many types, and packs type several values in a row. The new type solver is general release, and m14-ship runs luau-lsp analyze in CI.

Type annotations is labels on jars, until labels are checked before the game runs, and only then. While it runs, nothing reads them, so a value that arrives from a client or a DataStore can be anything whatever its label says.

Next Client and server: who owns what

Open this step in lesson mode · Link to this step · This confused me