TypeChecking and Custom Types Giving Error

Hi, I’m trying to use strict type checking, and creating custom types using unions but the type checker says it is expecting a table type as opposed to the custom type I’ve declared it as, and I’m not sure why.

'Exact error:

W000:Expected type table, got 'BoolValue | BrickColorValue | CFrameValue | Color3Value | IntValue | NumberValue | ObjectValue | RayValue | StringValue | Vector3Value instead.'

in

function onVariableChanged(Variable: VariableType, newValue: ValueType)
	if (type(newValue) == type(Variable.Value)) then
		**Variable.Value** = newValue
		return Anim:WarnCode(0x60)
	else
		return Anim:WarnCode(0x61, true, "Type of value doesn't match value type accepted by variable type.")
	end
end

Type error is specifically where I’ve double star quoted.

Type declared above as:

type VariableType = (BoolValue | BrickColorValue | CFrameValue | Color3Value | IntValue | NumberValue | ObjectValue | RayValue | StringValue | Vector3Value);

Many thanks for any insights!

1 Like

How do you define ValueType?

Also, use typeof instead of typetype will just give you "userdata" for all of those types.

Actually, pretty sure this is just a limitation of the type system + a bad/wrong error message.

Without generics, which are currently disabled in functions and wouldn’t be flexible enough for this anyways, I don’t think this is currently possible.

What you want to do is something like this in TypeScript:

// typescript not lua
type ValueBase = {
    Value: any;
}

type CFrameValue = {
    Value: "CFrame"
}

type BoolValue = {
    Value: "Bool"
}

function onVariableChanged<VariableType extends ValueBase>(Variable: VariableType, newValue: VariableType["Value"]) {
    Variable.Value = newValue;
}

But roblox’s type system isn’t quite that powerful yet.

Since your code is sound you can just use a hack type assertion:

function onVariableChanged(Variable: VariableType, newValue: any)
	if (typeof(newValue) == typeof(Variable.Value)) then
		(Variable :: any).Value = newValue
		return Anim:WarnCode(0x60)
	else
		return Anim:WarnCode(0x61, true, "Type of value doesn't match value type accepted by variable type.")
	end
end
4 Likes