Menu
CoddyTech

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

Check what userInput holds before you use it as a string.

  1. Under the comment, write if typeof(userInput) == "string" then.
  2. Inside it, print string.upper(userInput).
  3. Add an else branch that prints "Not a string", then close with end.

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

Practice on your own: Online Luau compiler