I use a file of exported constant as preprocessor directives. Now I would like to completely strip the body of a constructor if this directive is set. For example:
const MY_PREPROCESSOR_DIRECTIVE = true;
class Foo {
someProp: string;
constructor() {
if (MY_PREPROCESSOR_DIRECTIVE) return;
this.someProp = "string";
}
}
This works nicely, I'm using closure compiler for building, which strips the body and the whole thing is turned into only just:
class Foo {}
In TypeScript this causes errors though, because someProp and otherProp are "not definitely assigned in the constructor". And in JavaScript files, I don't get errors in the constructor, but all properties are getting set to string | undefined:
const MY_PREPROCESSOR_DIRECTIVE = false;
class Foo {
constructor() {
if (MY_PREPROCESSOR_DIRECTIVE) return;
this.someProp = "string";
}
myMethod() {
if (MY_PREPROCESSOR_DIRECTIVE) return;
this.someProp.substring(0);
// ^^^^^^^^^^^^^------ Object is possibly 'undefined'.
}
}
(js playground | ts playground)
Is there a way to let TypeScript know the directive will always be false so that it doesn't mark this.someProp as string | undefined? I tried to mark the return statement of the constructor as unreachable code, but I'm not sure how to achieve this.