Can you type check with functions?

function Function(Value)
    return Value
end

Function(function()

end)

Function("")

I want to know if I can type check for functions without using type() or typeof()
Value: function obviously doesn’t work for this

thanks for helping if you did

2 Likes

Why are you trying to avoid using type/typeof?

this is mainly out of curiosity, I am still using them

function Function(functionArg)
	local funcStr = tostring(functionArg)
	if string.match(funcStr, "^function: "..string.rep("%w", 18).."$") then
		print("Is a function.")
	else
		print("Is not a function.")
	end
end

Function(function() end)

not exactly what I meant
I meant this kind of type checking

function Function(Number: number, String: string, Any: any)

end
1 Like

Yes, and it looks just like that. But this is just a static analysis; it doesn’t actually enforce code to adhere to it. If you add --!strict on the first line of your script, it will underline code in red that violates the types.

If you want to enforce during runtime, you’ll have to use assertions.

3 Likes

I realize that, but my question is if I can type check functions

not really sure how I could do that

If I understand you correctly, then also yes. You can define a function type as such:

type SomeFunc = (number, string, any) -> nil
4 Likes
type Function = (any) -> nil

function Function(Function: Function)
	
end

so this seems to work fine
my only concern is if it will work every time

the Function type checks all types and if the value isn’t any of those types it works
I doubt functions are the only thing excluded from the type list, so I am not sure if this only works on functions or not

You can write what type the function will return and the type of parameters that will be returned too.

local function addNumbers(a: number, b: number): number
    return a + b
end

addNumbers(1, 2)

In the example I’ve displayed above, the a and b parameters return a number and : number written right next to the function parenthesis is the type of value the function will return.

1 Like
function Function(fn:(any)) : any
--:(any) can be replaced, for an instance - :(string)
--It reflects the args that need to be passed by into a given function "fn"
    return fn :: any
end

Function(function()

end)

Function("")
--Error, type "string" can't be converted to type "([typecheck])"

P.S. Indeed I didn’t mean to revive old topics but came upon searching for the function type-check and immediately got an answer so I decided to note it here.