TExcelTAD
Home › Godot 4 with GDScript › Static Typing

Static Typing

GDScript is gradually typed. You can write var hp = 100 and let the value decide the type at run time, or write var hp: int = 100 and let the compiler check every use. Both are legal, and you can mix them in one file. Professional Godot code types almost everything, for three reasons:

  1. Errors at edit time. Assigning a String to an int variable, calling a method that doesn't exist, or passing the wrong argument type is reported in the script editor before you press Play.
  2. Autocomplete. When the editor knows player is a CharacterBody2D, typing player. lists velocity, move_and_slide() and the rest.
  3. Speed. With known types, the GDScript VM uses typed instructions that skip run-time type checks. Typed math and property access are measurably faster in hot loops.

Declaring types

Form Meaning
var hp: int = 100 explicit type
var speed := 4.5 inferred from the value (float here); the type is fixed from then on
var anything = 10 untyped: a Variant that can later hold any value
const MAX_HP := 100 typed constant
func heal(amount: int) -> void: typed parameter and return value
func get_name() -> String: the function must return a String on every path
gdscript · try it yourself
extends SceneTree

func damage_after_armor(damage: int, armor: float) -> int:
	return int(damage * (1.0 - armor))

func _init():
	var hp: int = 100
	var speed := 4.5            # inferred as float
	var title := "Knight"       # inferred as String
	var anything = 10           # untyped: a Variant that can hold anything
	anything = "now a string"
	print(type_string(typeof(hp)), " ", type_string(typeof(speed)), " ", type_string(typeof(title)), " ", type_string(typeof(anything)))
	hp = 7.9                    # float assigned to an int: truncated
	print("hp = ", hp)
	print(damage_after_armor(40, 0.25))
	var ratio: float = 7 / 2    # integer division happens first
	print(ratio, " ", 7 / 2.0)
	quit()
int float String String
hp = 7
30
3.0 3.5

Two traps hide in that output. hp = 7.9 silently drops the fraction (the editor shows a narrowing conversion warning), and 7 / 2 is integer division even when the result goes into a float (an integer division warning). Write 7 / 2.0 or float(a) / b when you want a fraction.

The := pitfall: inferring from a Variant

:= infers the type from the right-hand side. That fails when the right-hand side has no known type, which is the case for dictionary lookups, untyped arrays, JSON.parse_string() and most get()-style calls: they return Variant. Godot refuses to infer from a Variant (the INFERENCE_ON_VARIANT warning is an error by default):

gdscript
var info := {"hp": 10}
var hp := info["hp"]          # Parse Error: Cannot infer the type of "hp" variable
                              # because the value doesn't have a set type.
var hp2: int = info["hp"]     # OK: you state the type, Godot converts at run time

The fix is always the same: write the type yourself.

Typed arrays and typed dictionaries

Array[T] only accepts values of type T, and elements read from it are known to be T, so the loop variable in for s in scores is typed too. Since Godot 4.4, dictionaries can be typed as well: Dictionary[KeyType, ValueType].

gdscript · try it yourself
extends SceneTree

func _init():
	var scores: Array[int] = [30, 12, 55]
	scores.append(8)
	scores.sort()
	print(scores, " max ", scores.max())
	var names: Array[String] = ["ada", "bo"]
	var upper := names.map(func(n: String) -> String: return n.to_upper())
	print(upper, " is typed: ", upper.is_typed())
	var stock: Dictionary[String, int] = {"potion": 3, "arrow": 20}
	stock["potion"] -= 1
	print(stock, " key type ", type_string(stock.get_typed_key_builtin()))
	var info := {"hp": 10}
	var hp: int = info["hp"]        # explicit type: fine
	print(hp + 1)
	var copy: Array[int] = []
	copy.assign([4, 5, 6])          # fill a typed array from an untyped one
	print(copy)
	quit()
[8, 12, 30, 55] max 55
["ADA", "BO"] is typed: false
{ "potion": 2, "arrow": 20 } key type String
11
[4, 5, 6]

Note that map() returns an untyped Array even on a typed array. To keep the type, declare the target (var upper: Array[String] = []) and call upper.assign(names.map(...)). Assigning an untyped array literal directly to a typed variable works, but assigning an untyped Array variable to an Array[int] fails at run time (Trying to assign an array of type "Array" to a variable of type "Array[int]"); use assign() for that.

is and as: checking and casting

Many APIs return a general type: get_node() returns Node, body_entered gives you a Node2D, get_children() gives Array[Node]. Use is to test the real class and as to cast. as returns null when the object isn't of that type (instead of raising an error), so check the result:

gdscript · try it yourself
extends Node

# frames: 0
func _ready():
	var sprite := Sprite2D.new()
	sprite.name = "Sprite"
	add_child(sprite)
	var label := Label.new()
	label.name = "Score"
	add_child(label)
	for child in get_children():
		if child is Node2D:
			print(child.name, " is a Node2D at ", (child as Node2D).position)
		elif child is Control:
			print(child.name, " is a Control")
	var wrong := get_node("Score") as Sprite2D
	print("Score as Sprite2D: ", wrong)
	var s := get_node("Sprite") as Sprite2D
	if s:
		s.offset = Vector2(4, 4)
		print("offset set to ", s.offset)
	var n: Node = $Sprite
	print(n is Sprite2D, " ", n is CanvasItem, " ", n.get_class())
Sprite is a Node2D at (0.0, 0.0)
Score is a Control
Score as Sprite2D: <null>
offset set to (4.0, 4.0)
true true Sprite2D

is follows inheritance: a Sprite2D is a Node2D, a CanvasItem and a Node. It also works with your own class_name classes (see Classes, class_name & Enums). For built-in value types, convert instead of casting: int("12"), str(5), float(x).

Make the editor strict

The warnings that push you towards full typing are off by default. Turn them on in Project > Project Settings > General > Debug > GDScript (enable Advanced Settings at the top right to see them). Each one can be Ignore, Warn or Error:

Setting (debug/gdscript/warnings/...) Reports
untyped_declaration any variable, parameter or function without a type
inferred_declaration := (for teams that want every type written out)
unsafe_property_access / unsafe_method_access x.foo when Godot can't prove x has foo
unsafe_cast as casts from a Variant
unsafe_call_argument passing a Variant where a typed parameter is expected
inference_on_variant := from a Variant (Error by default)

A good team setting is untyped_declaration = Warn (or Error) plus the unsafe_* warnings = Warn. Code in res://addons is excluded from warnings by default (the directory_rules setting), so third-party plugins don't flood your list. The script editor also turns the line number of every type-safe line green (you can switch this off or change the colour in the Editor Settings), so you can see at a glance where Godot falls back to dynamic checks.

Tip: @warning_ignore("integer_division") above a line silences one warning on purpose. Use it sparingly and leave a comment explaining why.

Test yourself

Why does var hp := data["hp"] fail when data is an untyped Dictionary?

  1. Dictionaries can't hold ints
  2. The lookup returns a Variant, and := can't infer a type from a Variant
  3. := only works with constants
  4. Keys must be StringName

What does get_node("Score") as Sprite2D return when Score is a Label?

  1. The Label
  2. A runtime error
  3. null
  4. A new Sprite2D

What does var r: float = 7 / 2 store?

  1. 3.5
  2. 3.0
  3. 4.0
  4. It doesn't compile