Refining a union type

Is there a way to refine a union type down to a single type in a --!strict script?
I know you can do something like this if both types inherit Instance with the IsA method, but this only useful for Instance-inheriting types, is there a way to do this with non-Instance types?

Here is an example of what I’m trying to achieve:

-- GetSomething is just some arbitrary function
local SomeVariable:TypeA|TypeB = GetSomething()
-- Something is of type (TypeA|TypeB), a union type between TypeA and TypeB

if SomeVariable is TypeA then
  -- SomeVariable is of type TypeA
  
  -- blah blah blah
end

This may be a bit of a random tidbit, but in C#, I’m able to do something similar, as it’s an important feature of the language. It doesn’t have union types, but a similar situation can be found with inheritance (Instance types do this).

public abstract class TypeAOrB { // This type is abstract and therefor cannot be instantiated, but can still be used for variable types and inheritance by other classes (assuming those classes implement all abstract members or is also abstract)
  // ...
}

// Both of these types inherit TypeAOrB, because of this, a variable of type TypeAOrB can contain an instance of TypeA or TypeB
public class TypeA : TypeAOrB {
  // ...
}
public class TypeB : TypeAOrB {
  // ...
}
TypeAOrB someVariable = GetSomething();

if (someVariable is TypeA) {
  // someVariable is of type TypeA
  // ...
}

If this feature isn’t in Luau, an alternative would be great, any help would be appreciated :D.

You’re probably thinking of typeof, which returns a string of the data type.

Here’s a few examples with some basic data types:

print(typeof(workspace.Baseplate)) -- "Instance"
print(typeof(Instance.new("ParticleEmitter"))) -- "Instance"
print(typeof("mystring")) -- "string"
print(typeof(123)) -- "number"
print(typeof(Vector3.zero)) -- "Vector3"

Yes, but typeof doesn’t return custom types (which is what the OP needs)

type TypeA = { index: "value" }

local var: TypeA = { index = "value" }
print(typeof(var)) --> "table"
2 Likes