Function (return) as luau type

I want to create a type that is essentially what a function returns. ex.

function Ibuf()
	return {
		alt = "ernative"
	}
end

type Ib = Ibuf

function Eru(Var : Ib)
	-- then as I type "Var", intellisense would give me something relevant
    -- showing me an option called "alt" that's supposed to be a string
end

What’s the most convenient way of doing something like this?

1 Like

So you’re trying to create a function that returns what said function is returning?

1 Like

I’m trying to use intellisense.

1 Like

You gotta add the table to the type without the function.

type Ib = {
alt: string
}

Then if you want to signal that the function returns that type then add this:

function Eru(Var: Ib): Ib
1 Like

That works for this case, but with a more complicated return:

function Ibuf()
	local object = {
		goddamn = "thisnoise",
		insidemy = "head",
		bot = true,
		skipper = math.random(1, 3)
	}
	
	function object:noway(victim : BasePart)
		victim.Parent = nil
	end
	
	function object:print(a : number, b : number, c : number)
		print(a)
		print("----- . -----")
        print(b + c)
		print(b .. "eheheh" .. c)
	end

    return object
end

Manually writing down types for all of it just to get intellisense after saying “this function should use what Ibuf returns” gets ridiculous.

1 Like

Small price to pay for intellisense to be honest.
I’ve literally had to deal with no IntelliSense for my class objects for 1.5years because I use a class module called MiddleClass.

The way that works is via metamethods and causes basic intellisense to get lost.
I just recently discovered that this type stuff can bring back intellisense and managed to use it properly with it.

It may seem like alot but if you’re doing one and done things, some extra time with types isn’t so bad if you don’t have to review the code every 5 minutes for args.

I’d highly recommend you read up on types and practice them.
May look a little challenging but once you get it down it’s not that hard.

2 Likes

You can do this by doing type Ib = typeof(Ibuf()), which will create a type for the return type of the function

2 Likes

Works great. I’m guessing that the table Ibuf returns in this case will be garbage collected, since there are no working references to it?

Types only exist at compile time, and do not effect the code at runtime what-so-ever, they are effectively stripped out of your code when it runs, so you don’t have to worry about it existing or running when you put them in.

1 Like