Explicit Type Annotations
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 11 of 73.
Knowing when to write annotations and when to lean on inference is a core Luau skill. The most common case that needs an explicit annotation: declaring a variable without an initial value.
local score: number -- no value yet — annotate the intent
score = 85 -- assigned later, checked against numberWith no initializer there's no value to infer from. In the default nonstrict mode an unannotated, uninitialized variable is treated as any — losing the safety you came to Luau for. The explicit : number locks the intended type from the start, so only numbers can ever be assigned:
local score: number
score = "85" -- ✗ type error: string is not a numberAt runtime, remember, a declared-but-unassigned variable simply holds nil until the assignment happens — the annotation documents and enforces what it will hold.
Annotations also shine wherever the type isn't obvious from the code: function parameters, return types, and empty tables you'll fill later. Rule of thumb — infer when the value is right there, annotate when it isn't.
Challenge
EasyDeclare a variable named totalScore with the explicit type number, without assigning an initial value. On the next line, assign it the value 95.
Then declare a variable named playerName with the explicit type string, again without an initial value. On the next line, assign it the value "Alex".
Finally, print both variables on separate lines — first totalScore, then playerName.
Try it yourself
-- Write code here
-- 1) declare totalScore: number (no value), then assign 95
-- 2) declare playerName: string (no value), then assign "Alex"
-- 3) print totalScore, then playerName
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps