Passing Luau types as arguments & type extensions

In many languages such as C++ or Java, it is possible to pass type arguments such as:

SomeFunction<MyType>()

This allows for further abstraction and would be a fantastic extension to the Luau language. Currently it is possible to do this via passing a value which holds the type you are interested in. This is okay but is ugly to work with, and also slower and less intuitive.

This is a very over-simplified example, in reality these would be massive objects such as Items which contain functions and various other things.

type parentType = {
	id: string,
}

type type1 = {
	x: number?,
} & parentType

type type2 = {
	y: number?,
} & parentType

local cache: {[string]: parentType} = {}

function fetch<T>(id: string): T
	local result = cache[id]
	if result then
		return result::any
	end
	local result = {
		id = id,
	}
	cache[id] = result
	return result::any
end

function fetch2<T extends parentType>(id: string): T -- I don't like this, but this kind of functionality would be preferablle
	local result = cache[id]
	if result then
		return result::any
	end
	local result = {
		id = id,
	}
	cache[id] = result
	return result::any
end

function tester()
	local x: type1 = fetch("abc") -- current workaround, inherently unsafe because (see below)
	local x: number = fetch("xyz") -- valid??
	local z = fetch<type1>("abc") -- proposed
end

Thank you!

Joe

4 Likes

support since i also wanna pass types into function generics explicitly

although this should be brought to luau engineers, its been mentioned a lot around the luau suggestions

FWIW the specific syntax you are proposing is ambiguous to add. Recreating a famous Rust test…:

return a<b, c>(d)

This today parses as returning two values, one being a < b and another c > d.

We also unfortunately cannot yoink the Rust Turbofish (::<T>()) specifically as it causes problems with type casts.

1 Like

I’ve been wondering how to do this for a while now, is there a way there could be a different syntax for it if those don’t work? This is really useful.

Syntax was more suggestive than anything, just looking for something to fill the purpose. Open to ideas. Would be very thankful for this extension in our project for inventories. Thank you!

2 Likes