In our code, we encountered a scenario where we had a class that needed to serve as both an object and an interface. The class had a cumbersome long name, so we decided to assign it to a constant. However, when we attempted to use this constant, we faced some unexpected issues:
class MyClassWithAReallyLongNameThatIsAnnoyinToUse {
constructor(public name: string) {}
static className = "SomeThing:MyClassWithAReallyLongNameThatIsAnnoyinToUse";
}
// Constant for convenience
const MyClassConst = MyClassWithAReallyLongNameThatIsAnnoyinToUse;
let someFunction = (staticClassObject: Object, callback) => {};
// An error occurred - 'Cannot find name MyClassConst'
someFunction(MyClassConst, (cmd: MyClassConst) => { /* perform some action */ });
Strangely enough, adding a type
alias right after the const
declaration resolved the issue:
class MyClassWithAReallyLongNameThatIsAnnoyinToUse {
constructor(public name: string) {}
static className = "SomeThing:MyClassWithAReallyLongNameThatIsAnnoyinToUse";
}
// Constant for convenience
const MyClassConst = MyClassWithAReallyLongNameThatIsAnnoyinToUse;
type MyClassConst = MyClassWithAReallyLongNameThatIsAnnoyinToUse; // <<<<<<<<<<<<<
let someFunction = (staticClassObject: Object, callback) => {};
// No issues with this implementation
someFunction(MyClassConst, (cmd: MyClassConst) => { /* perform some action */ });
This situation raises concerns as we seem to be modifying a constant and defining the same thing twice with different keywords. Surprisingly, using the actual long class name directly instead of the constant works seamlessly. The problem only arises when the class is accessed through the constant (or other variable declarations).
Should we just accept this behavior as a quirk of the language, or is there a way to retrieve the type from the constant? Perhaps there is another approach we have overlooked?