Back to Luau

Generics and Polymorphism

types-generics.md

latest4.8 KB
Original Source

Generics and Polymorphism

The type inference engine was built from the ground up to recognize generics. A generic is simply a type parameter in which another type could be slotted in. It’s extremely useful because it allows the type inference engine to remember what the type actually is, unlike any.

Embedded content

Generic functions

Section titled “Generic functions”

As well as generic type aliases like Pair<T>, Luau supports generic functions. These are functions that, as well as their regular data parameters, take type parameters. For example, a function which reverses an array is:

Embedded content

The type of this function is that it can reverse an array, and return an array of the same type. Luau can infer this type, but if you want to be explicit, you can declare the type parameter T, for example:

Embedded content

When a generic function is called, Luau infers type arguments, for example

Embedded content

Generic types are used for built-in functions as well as user functions, for example the type of two-argument table.insert is:

<T>({T}, T) -> ()

Note: Functions don’t support having defaults assigned to generics, meaning the following is invalid

Embedded content

Generic type instantiation

Section titled “Generic type instantiation”

By default, Luau will infer the type arguments when calling a generic function. You can also provide them explicitly using the syntax func<<Type>>(...). This is called generic type instantiation or just type instantiation. For example,

Embedded content

Explicit instantiation is useful when inference would be ambiguous or when you want to constrain the inferred type to a supertype:

Embedded content

You can also instantiate multiple type parameters at once by separating them with commas:

Embedded content