The 'unknown' Type
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 8 of 80.
Like any, a variable of type unknown can hold any value:
local userInput: unknown = "Hello"
userInput = 42 -- no error
userInput = true -- no errorThe key difference: the checker won't let you use an unknown value until you've verified what it actually is. You narrow it with a typeof() check:
local data: unknown = "Luau"
-- string.upper(data) -- ✗ type error: data might not be a string
if typeof(data) == "string" then
print(string.upper(data)) -- ✓ safe: data is a string here
endInside the if block, the checker narrows data to string: the check proved it, so string operations are allowed. typeof(x) returns the type name as a string: "number", "string", "boolean", "table", "nil"…
This makes unknown much safer than any: both hold anything, but unknown forces you to check before you touch, so the mistakes any lets through never get written.
Challenge
EasyCheck what userInput holds before you use it as a string.
- Under the comment, write
if typeof(userInput) == "string" then. - Inside it, print
string.upper(userInput). - Add an
elsebranch that prints"Not a string", then close withend.
Press Run Code: the output shows LUAU.
Try it yourself
-- userInput can hold anything, but must be checked before use
local userInput: unknown = "Luau"
-- Write the typeof check here
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 ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe '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 TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler