Using type fields as their own types

When I am using predefined types I often need to refer to the type in related code. For example I might want to cast to the type:

local B = SomethingElse :: B_Type
B.Field = "Hello"

Or I might want to create a variable of it some time before it gets stored into its final location:

local B: B_Type = {
   Field = "Hello";
}
...
Storage.B = B

This is fine if I have only a single type in play, like B_Type, but it gets a bit more complicated if I have more layers of nesting, like so:

type A = {
	B: {
		Field: string;
	};
}

In this case, to be able to do the two examples above, I need to define the subtype B separately from the parent type A:

type A = {
   B: B;
}
type B = {
   Field: string;
}

local B = SomethingElse :: B
B.Field = "Hello"

local B: B = {
   Field = "Hello";
}

A.B = B

This verbosity is sometimes desirable for other reasons. But I often have small random subtypes which for all intents and purposes are only relevant to their parent type. In that case, it would be more compact and easier for me to just define the subtype all under A and refer to the subtype as A.B.

type A = {
	B: {
		Field: string;
	};
}

local B = SomethingElse :: A.B
B.Field = "Hello"

local B: A.B = {
   Field = "Hello";
}

A.B = B

For generic indexes into tables maybe we could just use empty brackets? e.g. local B: A[] to refer to the type of an element of the array type A = {B}, and same for dictionaries like type A = {[string]: B}.

5 Likes

This is solved by using the index type function implemented in the New Luau Type Solver Beta.

Announcement describes this feature among others, but more info about the chosen design can be found in the RFC: index type function.

2 Likes

Great thanks. That syntax looks pretty cumbersome so I hope you guys add that syntactic sugar soon!

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