How do I add a function to a exported type?

Say I have a type named Permission and it’s declared as export type Permission = {}
How would I go about adding a function named something like new to it? I’m not sure if you can actually do this or not.

Maybe you need something like this
ModuleScript:

local module = {}

export type Point = {x: number, y: number}

function module:New(num: number): Point
	return {x=num, y=num*2}
end

return module

ServerScript/LocalScript:

local module = require(script.ModuleScript)
local mypoint: module.Point = module:New(2)
print(mypoint)

image

1 Like
export type Permission = {
    new: (parameters: TheirType) -> TypeOfValueItReturns
}
-- in case of multiple values, use parenthesis around the return.

ex.

export type Permission = {
    new: (player: Player, permission: number) -> Permission
}
1 Like

Thanks for the response, that’s pretty much what I want but I’m having a problem.

Whenever I try to make a variable with its type set to Permission, it says the variable was never initialised or assigned and suggests I set the variable to nil like

local NewPermission: Permission = nil
NewPermission.New(Player, 2)

But whenever I run the code, it says attempt to index nil with 'New'

That’s quite weird, can you show the current code and the “error” that said use nil?

local NewPermission: Types.Permission
NewPermission.New("Player", 2)

image

That’s because it has no value, you just gave it a type.

export type Permission = {
    new: (player: Player, permission: number) -> returnType
}

-- In another file:
local NewPermission: Types.Permission = {}

function NewPermission.new(player: Player, permission: number): returnType

end

NewPermission.New("Player", 2)
6 Likes

Works now, thanks.

[3 0 characters]

Your welcome. Feel free to ask any questions if needed.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.