Type checking OOP Help - Literal Values not working as intended

Hello! Its my first time using type checking and im really confused that literal values dont work as intended when I try and return in the .new() function.

It should work since Rarity is being set to “Rare” one of the choices I set in the begining of the script. Anybody know how to fix this? I’m using --!strict mode


--!strict

type self = {Name:string, Age: number, Rarity: "Common" | "Rare" | "Epic" | "Legendary"}

type AnimalImpl = {
	__index: AnimalImpl,
	new: (name: string, Rarity: "Common" | "Rare" | "Epic" | "Legendary") -> Animal,
	Die: (self: Animal) -> number,
}

export type Animal = typeof(setmetatable({} :: self, {} :: AnimalImpl))

local Animal = {} :: AnimalImpl


Animal.__index = Animal

function Animal.new(Name, Rarity)

	local self = {}

	self.Name = "Todd"
	self.Age = 0
	self.Rarity = "Rare"

	return setmetatable(self, Animal)
end

function Animal:Die(): number
	local corpse = 1

	print(self.Name:: string .. "is dead")

	return corpse
end

return Animal

Does not have a type defined.
you would want to do

	local self:self = {
		Name = "Todd",
		Age = 0,
		Rarity = "Rare"
	}

Ohh, tysm. Makes much more sense now

also found variation of your solution is this:
image

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