Menu
Coddy logo textTech

Generic Type Aliases

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

Functions aren't the only things that can take a type parameter — type aliases can too. That lets you describe a whole family of table shapes at once:

type Box<T> = {value: T}

A Box is a table with one field, value — and T decides what the field holds. Unlike a function call, using a generic alias in an annotation means writing the concrete type in the angle brackets:

local numberBox: Box<number> = {value = 42}
local stringBox: Box<string> = {value = "Luau in a box"}

Box<number> and Box<string> are two different types stamped from the same template. Put a string into a Box<number>'s value and the checker objects immediately.

Generic aliases and generic functions are made for each other. A function can accept any box and give back exactly what's inside — note how T flows from the parameter's type into the return type:

local function unbox<T>(box: Box<T>): T
    return box.value
end

Call unbox(stringBox) and the checker knows the result is a string — the type parameter carried the information all the way through. This alias-plus-function pattern is the foundation of the inventory project coming in the next chapter.

challenge icon

Challenge

Easy

Build the box pattern yourself.

Define a generic type alias named Box with a type parameter T, describing a table with a single field value of type T.

Create a generic function named unbox that:

  • declares a type parameter T
  • accepts one parameter named box of type Box<T>
  • returns box.value, with return type T

Create these boxes:

  • numberBox of type Box<number> holding 42
  • stringBox of type Box<string> holding "Luau in a box"
  • boolBox of type Box<boolean> holding true

Print the following, each on its own line:

  1. numberBox.value
  2. the result of unbox(numberBox)
  3. the result of unbox(stringBox)
  4. the result of unbox(boolBox)

Try it yourself

-- Write code here
-- 1) define type Box<T> = {value: T}
-- 2) define unbox<T>(box: Box<T>): T
-- 3) create numberBox, stringBox and boolBox
-- 4) print numberBox.value, then unbox each box
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