The Problem Generics Solve
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 57 of 73.
Imagine you need a function that simply returns whatever value you pass to it — an identity function. With the types you know so far, you have two options, and both hurt.
Option one: write a separate copy per type. The bodies are identical; only the annotations differ:
local function echoNumber(value: number): number
return value
end
local function echoString(value: string): string
return value
endEvery new type means another copy, and a bug fixed in one must be fixed in all of them. That's exactly the duplication you write functions to avoid.
Option two: collapse them into one function typed with any:
local function echo(value: any): any
return value
endNow one function handles everything — but you've paid with type safety. When you call echo("hello"), the checker no longer knows the result is a string. It only knows any, so autocomplete goes dark and type errors slip through: the connection between what went in and what comes out is lost.
What you really want is a function that works for every type and remembers which type each call used. That is precisely what generics give you — and they're the subject of this chapter.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps6Typing Table Shapes
Inline Shape AnnotationsType Aliases for ShapesOptional PropertiesShapes vs. Loose TablesExtending ShapesAdding Methods to ShapesSelf and Colon MethodsRecap: Defining Table Shapes9Generics: A First Look
The Problem Generics SolveA Generic Identity FunctionUsing a Generic FunctionGeneric ArraysGeneric Type AliasesRecap: Generic Functions