Type Inheritance

I’m trying to create a system which implements a few class structures. These classes have different structures depending on which environment they are created in, but they use a common abstract definition.

So far, building the class types from there hasn’t been a problem, but I’ve run into problems trying to define subclasses which use their environment’s class definition for other classes. Here’s what I mean:

--!strict

--These proto classes would serve as the common template.

type proto_properties_class = {
	id: number,
	name: string
}
type proto_item = {
	properties: proto_properties_class,
	value: number
}

---------------------------------------------------
--These classes would use the environment-specific definitions for the classes.

type properties_class = {
	color: Color3
} & proto_properties_class

type item = {
	properties: properties_class,
} & proto_item

---------------------------------------------------
--Creating an object from the environment-specific definition causes a
--typechecking warning because the "properties" table has too many elements.

local item_object: item = {
	properties = {
		id = 1,
		name = "Item",
		color = Color3.new()
	},
	value = 1
}

Bear in mind that this example is arbitrary, but it should illustrate the point.

I understand why the typechecker has a problem with it, and I don’t disagree with its assessment, but I don’t quite get how to get around the problem while still being able to take advantage of the abstract classes. What is the proper way to implement abstract classes in the typechecker?

3 Likes

I have a fix by adding an assign type after each variable that had been defined by type so that I can make the type checking stop screaming by doing this:

--!strict

--These proto classes would serve as the common template.

type proto_properties_class = {
	id: number,
	name: string
}
type proto_item = {
	properties: proto_properties_class,
	value: number
}

---------------------------------------------------
--These classes would use the environment-specific definitions for the classes.

type properties_class = {
	color: Color3
} & proto_properties_class

type item = {
	properties: properties_class,
} & proto_item

---------------------------------------------------
--Creating an object from the environment-specific definition causes a
--typechecking warning because the "properties" table has too many elements.

local item_object: item = {
	properties = {
		id = 1,
		name = "Item",
		color = Color3.new()
	},
	value = 1
} :: item -- :: item stop type checking from screaming also will scream if you do any other type.

As for the part why it work. I have no idea.

Oh you can also do this

local item_object = { -- removed the : item
	properties = {
		id = 1,
		name = "Item",
		color = Color3.new()
	},
	value = 1
} :: item
4 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.