有没有办法避免这种情况:
class a {
p:any;
constructor() {
}
m() {
}
}
class b extends a {
p:any;
constructor() {
super();
}
m() {
}
}
我知道我可以创建私有属性,但是要从外部访问它们,我需要创建一个公共方法,所以问题仍然存在,因为方法在没有任何警告的情况下是"可重写的",但我找不到任何选项来避免这种情况。
我也可以创建setter和getter,但同样适用。
听起来你想要final
方法(子类被禁止重写的方法)。这个特性已经被TypeScript请求过了,但是在写这篇文章的时候,它还没有被接受。
这就是面向对象编程背后的思想…
注意,如果你改变类型,你会得到编译错误:
class A {
p: string;
}
class B extends A {
p: number;
}
你:
类'b'错误地扩展了基类'a'。
属性"p"的类型不兼容。
类型"number"不能赋值给类型"string"
方法也是如此:
class A {
m(): string {
return null;
}
}
class B extends a {
m(): number {
return null;
}
}
生产:
类'b'错误地扩展了基类'a'。
属性'm'的类型不兼容。
类型'()=>数字'不能赋值给类型'()=>字符串'。
类型"number"不能赋值给类型"string"
编辑
你不能真正重写属性。
以以下代码为例:
class A {
a: string;
constructor() {
this.a = "default";
}
}
class B extends A {
a: string;
setA(value: string) {
this.a = value;
}
}
当你在B
上声明它时,似乎你正在重写属性,但是如果你看看编译的js:
var A = (function () {
function A() {
this.a = "default";
}
return A;
}());
var B = (function (_super) {
__extends(B, _super);
function B() {
_super.apply(this, arguments);
}
B.prototype.setA = function (value) {
this.a = value;
};
return B;
}(A));
属性a
在赋值之前没有定义。
你可以认为编译器应该警告你重新定义一个现有的属性,但是你不能这样做:
interface X {
str: string;
}
interface Y extends X {
num: number;
}
class A {
a: X;
}
class B extends A {
a: Y;
}
同样,当涉及到方法时,ide应该在您重写方法时显示您,至少webstorm在左侧托盘中显示一个图标。