In TypeScript, I am attempting to create a class where properties are only accessible if another property has been checked on the class. This needs to be done in a generic manner to facilitate reuse across multiple classes.
For instance,
class Test {
FooEnabled: boolean = false;
Foo() {
}
}
const test = new Test();
//shouldn't be allowed, because we haven't checked FooEnabled
test.Foo();
//this should be allowed
if(test.FooEnabled) {
test.Foo();
}
The resulting type should be:
type TTT = {
other: string,
} & (
{FooEnabled: false} | {FooEnabled: true, Foo(): void}
) & (
{BarEnabled: false} | {BarEnabled: true, Bar(): void}
) & (
{BazEnabled: false} | {BazEnabled: true, Baz(): void}
) & (
{BayEnabled: false} | {BayEnabled: true, Bay(): void}
)
class Test {
other = "hello world";
FooEnabled: boolean = false;
Foo = () => void 0;
BarEnabled: boolean = false;
Bar = () => void 0;
BazEnabled: boolean = false;
Baz = () => void 0;
BayEnabled: boolean = false;
Bay = () => void 0;
BaxEnabled: boolean = false;
Bax = () => void 0;
}
//errors when enabling the `Bax` guard
const value: TTT = new Test();
I have successfully implemented this concept for up to 4 different "enabled" properties. However, upon adding a fifth property, the implementation breaks. The issue seems unrelated to the actual contents of what is enabled or disabled, but rather the quantity of guards being utilized.
This is the code snippet that currently works (refer to the provided playground link for complete code):
(...)
Overall, the mechanism functions well until more than 5 properties are added to the "Support Factory." Surpassing this threshold triggers an error when trying to cast the class into the InstanceImplements type.
Consequently, the following line generates an error:
const TEST: InstanceImplements<Test, TestSupportFactory> = new Test();
It remains unclear why this limitation arises. My assumption is that it may be related to a typescript restriction concerning unions.