godottypinggdscript

Godot GDScript Typing: Invalid Type Err


most basic example:

world.tscn (main-scene)

extends Node2D
const MYLIST = preload("res://my_list.tscn")

func _ready() -> void:
    var my_list = MYLIST.instantiate()
    add_child(my_list)
    my_list.initialization(["one", "two", "three"])

and my_list.tscn

extends Node2D
@onready var item_list: ItemList = $ItemList

func initialization(entries: Array[String]):
    for entry in entries:
        item_list.add_item(entry)


this gives me runtime-error: invalid type in function "initialization". The array of argument 1 (Array) does not have the same element type as the expected typed array argumen.

The argument i pass into my_list.initialization is clearly a Array[String] If i remove the type hint from the func declaration it works as expected.

Can someone explain whats wrong here? Thank you!


Solution

  • I do not know which version of Godot you are using, I would like to know so I can test in that specific version.

    I can tell it is Godot 4 because you have typed Arrays but the details have changed from version to version.

    If I recall correctly in Godot 4.0 this failed silently (no error, but you got an empty array), and after Godot 4.2 it seems to be working correctly. Thus, 4.1, probably?


    Godot does not have typed Array literals (although in recent versions it will scan the contents of the array to find if the literal is compatible with a typed Array).

    So the Array given by ["one", "two", "three"] is not a Array[String] but simply a Array, and your version of Godot might not be checking if it is compatible.


    So, aside from trying in a more recent version. I have three possible workarounds for you: