Declare types of function parameter?

Godot Version

4

Question

How can one declare that a parameter expects a function? And/or declare the types that that parameter function will take / return?

I’m coming from TypeScript, and that’s a pretty common operation there, with code similar to what’s below. But in GDScript I’ve tried extrafunc: (() -> void) = null, extrafunc: Function, etc in the parameters array and all of it’s giving me compiling error. The page on types doesn’t seem to include functions in the syntax it displays.

Thank you!


const string = "hello world";
const paramfunc = (key: String) => {
	return key.length;
}

function my_target_function(str: String, paramfunc: (key: String) => int) {
	return paramfunc(str);
}
my_target_function(string, paramfunc)

^ How to do this kind of thing in GDScript…?

It’s not possible to specify parameters in functions when specifying their type. You need to use the type Callable instead.

extends Node


var string = "hello world"
var paramfunc = func(key: String):
	return key.length()


func _ready() -> void:
	var len = my_target_function(string, paramfunc)
	print(len)


func my_target_function(str: String, paramfunc: Callable) -> int:
	return paramfunc.call(str)

Ah, gotcha. Too bad about no typing for func params, but thank you so much, Callable is what I was looking for!