How to get a class's type from within an inherited base class

Godot Version

4.5.1 stable

Question

I’m trying to create a clean reusable serialization system for my custom data classes

My goal is to have a base class SerializableObject, that handles the logic of serializing and deserializing itself. Any class that inherits from it should automatically gain this functionality without needing to write any boilerplate code

Here is the ideal structure I want to achieve:

# serializable_object.gd
extends RefCounted
class_name SerializableObject

func serialize() → Dictionary:
	# I need to pass ‘MatchData’ to the serializer.
	return Libs.Seriafy.serialize(self, ???) # <— THE PROBLEM

static func deserialize(data: Dictionary) → RefCounted:
	return Libs.Seriafy.deserialize(data, ???) # <— THE PROBLEM

Seriafy lib:

static func serialize(object: Object, default_class: Object = null) → Dictionary[String, Variant]:
var data: Dictionary[String, Variant] = {}
if default_class != null:
default_class = default_class.new()

var instance_dict: Dictionary = inst_to_dict(object)
instance_dict.erase('@subpath')
instance_dict.erase('@path')

for v: StringName in instance_dict:
	if v.begins_with('_'):
		continue
	
	if typeof(instance_dict[v]) == TYPE_DICTIONARY or typeof(instance_dict[v]) == TYPE_ARRAY:
		data[str(v)] = instance_dict[v].duplicate(true)
	else:
		data[str(v)] = instance_dict[v]

return data

static func deserialize(data: Dictionary, default_class: Object) → Object:
if default_class != null:
default_class = default_class.new()

for v: Variant in data:
	var value: Variant = data[v]
	default_class[v] = value

return default_class

And then

# all classes script
class MatchData extends SerializableObject:
	var gamemode_name: String = ''
	var map_name: String = ''
	var ct_score: int = 0
	var t_score: int = 0
	var timer: int = 0
	
	# I want to avoid writing serialize/deserialize methods here.
	# They should be inherited and work automatically.

class MessageData extends extends SerializableObject:
	var peer_id: int = -1
	var text: String = ''
	var date_time: int = -1

And I know that ideally there should be types to avoid unnecessary serialization, but so far there are no types in GDScript :frowning:

Any help would be greatly appreciated!

self.get_script()

Why not use Resource instead? Those serialize pretty well.