我使用导出常量的文件作为预处理器指令。现在,如果设置了此指令,我想完全剥离构造函数的主体。例如:
const MY_PREPROCESSOR_DIRECTIVE = true;
class Foo {
someProp: string;
constructor() {
if (MY_PREPROCESSOR_DIRECTIVE) return;
this.someProp = "string";
}
}
这工作得很好,我正在使用闭包编译器进行构建,它剥离了主体,整个事情只变成了:
class Foo {}
然而,在TypeScript中,这会导致错误,因为someProp
和otherProp
是"0";在构造函数中没有明确指定";。在JavaScript文件中,我在构造函数中没有得到错误,但所有属性都被设置为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操场|ts操场(
有没有办法让TypeScript知道该指令将始终为false,这样它就不会将this.someProp
标记为string | undefined
?我试图将构造函数的return
语句标记为不可访问的代码,但我不确定如何实现这一点。
由于TS对bout runtime
MY_PREPROCESSOR_DIRECTIVE`一无所知,我认为值得使用策略模式。
因此,您有Foo
类的两个变体。一个是CCD_ 9,另一个是用CCD_。
const MY_PREPROCESSOR_DIRECTIVE = false;
interface Foo {
someProp?: string;
myMethod: () => void
}
class WithDirective implements Foo {
someProp: string;
constructor() {
this.someProp = "string";
}
myMethod() {
this.someProp.substring(0)
}
}
class WithoutDirective implements Foo {
someProp: undefined
constructor() { }
myMethod() { }
}
const Foo = MY_PREPROCESSOR_DIRECTIVE ? WithDirective : WithoutDirective
游乐场
如果你不喜欢构建中总是有一个未使用的类,你可以使用类表达式:
const MY_PREPROCESSOR_DIRECTIVE = false;
interface Foo {
someProp?: string;
myMethod: () => void
}
const Foo =
MY_PREPROCESSOR_DIRECTIVE
? class implements Foo {
someProp: string;
constructor() {
this.someProp = "string";
}
myMethod() {
this.someProp.substring(0)
}
}
: class implements Foo {
someProp: undefined
constructor() { }
myMethod() { }
}
就我个人而言,我认为第一个例子可读性更强,更容易维护。此外,我认为这不会对您的捆绑包大小产生重大影响。
在JavaScript中,解决这个问题的一种方法似乎是使用JSDoc:显式设置类型
constructor() {
if (MY_PREPROCESSOR_DIRECTIVE) return;
/** @type {string} */
this.someProp = "string";
}
(操场(
我不确定是否有类似的方法来处理TypeScript,所以这很可能是无意的行为。