The 'unknown' Type
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 8 of 73.
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
EasyCreate a variable named userInput with the type unknown and assign it the string "Luau".
Then write a type guard using typeof: if userInput is a string, print its uppercase version (use string.upper); otherwise print Not a string.
This shows how unknown requires a check before you can safely use string functions.
Try it yourself
-- Create the userInput variable with the unknown type
local userInput: unknown = "Luau"
-- Write code here
-- 1) check typeof(userInput) == "string"
-- 2) if so, print string.upper(userInput)
-- 3) otherwise print "Not a string"
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