Menu
Coddy logo textTech

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 error

The 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
end

Inside 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 icon

Challenge

Easy

Create 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"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau