🧠 GDScript Type Checking: Human-Readable Output
When you use typeof()
in GDScript, it returns a number representing the data type:
print(typeof(1)) # Output: 2
print(typeof("hello")) # Output: 4
These numbers correspond to internal engine enums like TYPE_INT
, TYPE_STRING
, and so on—but they’re not very readable to beginners.
🧩 Making Types Readable with a Custom Helper
Let’s fix that! We can make these type values human-readable using a small custom helper class.
✨ Variant.type_name()
Here’s a class that translates Godot’s internal type codes into names:
class Variant:
static func type_name(type):
match type:
TYPE_NIL: return "null"
TYPE_BOOL: return "bool"
TYPE_FLOAT: return "float"
TYPE_STRING: return "string"
_:
return "unknown"
Now instead of this:
print(typeof("hello")) # Just prints 4
You can do:
print(Variant.type_name(typeof("hello"))) # Prints "string"
🧪 Let’s Try It Out
Here’s a quick example using three different values:
func _ready() -> void:
var val1 = "hello"
var val2 = 1
var val3 = 1.123
print("................")
print(Variant.type_name(typeof(val1))) # string
print("................")
print(Variant.type_name(typeof(val2))) # int
print("................")
print(Variant.type_name(typeof(val3))) # float
print("................")
🧾 Code Explanation: Line-by-Line
🧱 class Variant
A custom class—not the built-in Godot Variant
—used here to teach how match
works and return readable names.
⚙️ static func type_name(type)
A static method means you don’t need to instantiate the class. You can call it directly with:
Variant.type_name(typeof(value))
🔀 The match
Block
This works like a switch-case. Each constant (like TYPE_FLOAT
) is matched to a return string.
❓ _:
(Fallback)
If the type
doesn’t match any known case, "unknown"
is returned.
🔍 Real-World Use Case
Here’s what happens when you try this:
print(Variant.type_name(typeof(true))) # bool
print(Variant.type_name(typeof("Hi"))) # string
print(Variant.type_name(typeof(42.0))) # float
This makes debugging way easier than staring at cryptic numbers!
✅ Why This Matters
typeof()
helps you know what you’re working with.- Human-readable names make debugging simpler.
- This tiny helper builds your confidence while learning dynamic typing.
- Great practice for understanding enums, static methods, and match expressions.
🧠 Bonus Tip
Godot does have a built-in method Variant.get_type_name()
—but using your own lets you understand what’s happening under the hood.