World 1-1 The Fundamentals : GDScript intro

Part 13: Creating a Helper Class for Readable Types in GDScript

Learn how to turn Godot's typeof() results into clear, human-readable types like 'int', 'float', and 'string'—perfect for debugging and beginners

🧠 GDScript Type Checking: Human-Readable Output

When you use typeof() in GDScript, it returns a number representing the data type:

gdscript
1
2
3
4

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:

gdscript
1
2
3
4
5
6
7
8
9
10
11

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:

gdscript
1
2
3

print(typeof("hello"))  # Just prints 4

You can do:

gdscript
1
2
3

print(Variant.type_name(typeof("hello")))  # Prints "string"

🧪 Let’s Try It Out

Here’s a quick example using three different values:

gdscript
1
2
3
4
5
6
7
8
9
10
11
12
13
14

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:

gdscript
1
2
3

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:

gdscript
1
2
3
4
5

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.

SightlessDev