在TypeScript中,const关键字不能用于声明类属性.这样做会导致编译器出错,"类成员不能拥有'const'关键字."
我发现自己需要在代码中清楚地指出不应该更改属性.如果我在声明属性后尝试为该属性分配新值,我希望IDE或编译器出错.你们是如何实现这一目标的?
我目前正在使用只读属性,但我是Typescript(和JavaScript)的新手,并想知道是否有更好的方法:
get MY_CONSTANT():number {return 10};
Run Code Online (Sandbox Code Playgroud)
我正在使用typescript 1.8.建议?
PS:我现在正在使用打字稿2.0.3,所以我接受了大卫的回答
我尝试使用实例方法中的静态成员.我知道从typescript中的非静态函数访问静态成员,但我不想硬编码该类以允许继承:
class Logger {
protected static PREFIX = '[info]';
public log(msg: string) {
console.log(Logger.PREFIX + ' ' + msg); // What to use instead of Logger` to get the expected result?
}
}
class Warner extends Logger {
protected static PREFIX = '[warn]';
}
(new Logger).log('=> should be prefixed [info]');
(new Warner).log('=> should be prefixed [warn]');
Run Code Online (Sandbox Code Playgroud)
我尝试过类似的东西
typeof this.PREFIX
Run Code Online (Sandbox Code Playgroud)