Can someone make a community tutorial on how to use autocomplete

Roblox Studio does it’s best autocompleting tables and stuff but sometimes it doesn’t know like in this example.

local PlayerProfiles = {}
PlayerProfiles.__index = PlayerProfiles

function PlayerProfiles.GetProfile(player)
	return PlayerProfiles[player]

function PlayerProfiles:AddBitcoin()

	PlayerProfiles[player] = setmetatable({}, PlayerProfiles)

return PlayerProfiles

As you can see here there are no suggestions:

And here there are suggestions:

Even though they are the same object.

Is there a way to help guide the autocomplete by explicitly telling it the return type? I know you can do

function PlayerProfiles.GetProfile(player): {}
	return PlayerProfiles[player]

but all this says is that it returns a table and not which specific table.

Thanks for the help

I recommend having a look at this section of this tutorial to familiarize yourself with how to make types for tables: Type checking for beginners!

It doesn’t include how to use it with metatables but it’s still easy enough to do once you know the typeof type operator exists.

Anyway, you have 2 options really:

1- Define a type that has all the members of whatever your profile class would have, such as:

type profileProps = { -- whatever would appear in the profile's properties

type profileMethods = {
	GetProfile: (player: Player) -> profile;
	AddBitcoin: (self: profile) -> ();
	[Player]: profile;
	__index: profileMethods;

type profile = typeof(setmetatable({} :: profileProps, {} :: profileMethods))

then have GetProfile’s return type be profile, ie:

function PlayerProfiles.GetProfile(player): profile
	return PlayerProfiles[player]

You can assert PlayerProfiles to be of type profileMethods to get self assigned a type in your profile methods

local PlayerProfiles = {} :: profileMethods


2- If you want profile to be an inferred type you need to make a function that creates a profile object instead.

local function makeProfile()
	local self = setmetatable({}, PlayerProfiles)
	return self

type profile = typeof(makeProfile())

Then you just make GetProfile’s return type to be profile, same as above

function PlayerProfiles.GetProfile(player): profile

In both cases you get your intended result:

1 Like

Thank You! This is exactly what I was looking for!

I always thought it was weird to do the first method you showed because then I would have to keep the profile type in sync with the profile object in order for it to be accurate. Almost like there were two sources of truth instead of one.

I never knew you could use typeof in this way

1 Like