Menu
Coddy logo textTech

Type Assertions

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 68 of 73.

Sometimes you know more about a value than Luau's type checker does — a value typed any that you know is really a user record, for example. A type assertion (also called a cast) lets you tell the checker "trust me, treat this value as this type". Luau's cast operator is :::

type User = {id: number, username: string}

local raw: any = {id = 42, username = "alice_dev"}
local user = raw :: User
print(user.username) -- the checker now knows the fields

A cast changes only what the type checker believes — it does nothing at runtime. It never converts a value: "5" :: any is still the string "5", not the number 5 (use tonumber for real conversion). And it never validates: if you assert the wrong type, the cast itself won't error — your code will simply misbehave later, when it touches fields that aren't there.

When to use it: when a value arrives as any (or a broad union) and you genuinely know its shape. When not to: to silence a type error you don't understand — the error is usually telling you about a real bug, and casting it away just hides it. Prefer real checks (like the typeof guards in the next lesson) when you can verify at runtime.

challenge icon

Challenge

Easy

Simulate processing records that arrive from an external source without type information.

  • Declare type User = {id: number, username: string, isActive: boolean}.
  • Write a function describeUser(data: any): string that casts data to User with :: and returns User [id]: [username] (Active: [isActive]) built with string interpolation.

The starter code already defines three raw records typed any. Call describeUser on each of them and print the three results, in order.

Expected first line: User 42: alice_dev (Active: true)

Try it yourself

-- Raw records from an external source: typed `any`
local rawUser1: any = {id = 42, username = "alice_dev", isActive = true}
local rawUser2: any = {id = 15, username = "bob_admin", isActive = false}
local rawUser3: any = {id = 99, username = "charlie_user", isActive = true}

-- Write code here
-- 1) declare the User type
-- 2) describeUser(data: any): string — cast with :: and build the message
-- 3) print the description of all three records
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