Menu
CoddyTech

Generic Type Aliases

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 65 of 80.

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

Describe a box that can hold any one type.

  1. Write type Box<T> = {value: T} and local function unbox<T>(box: Box<T>): T that returns box.value.
  2. Declare local scoreBox: Box<number> = {value = 77} and local nameBox: Box<string> = {value = "Coddy"}.
  3. Print unbox(scoreBox), then unbox(nameBox).

Press Run Code: the output shows 77 and Coddy.

Try it yourself

-- 1) type Box<T> and unbox<T>(box: Box<T>): T
-- 2) scoreBox: Box<number> and nameBox: Box<string>
-- 3) print unbox of each

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler