[英]TS: missing typings for optional members in implementation of abstract class that implements interface
Example:例子:
interface IFoo {
bar: number;
foo?: () => void;
}
abstract class AbstractFoo implements IFoo {
bar = 42;
};
Since foo
is optional, I don't need to implement it in AbstractFoo
.由于foo
是可选的,我不需要在AbstractFoo
实现它。 However, I can implement it in a child of AbstractFoo
.但是,我可以在AbstractFoo
的子项中实现它。 Therefore I expect the following code to not compile since foo
implemented wrong:因此,我希望以下代码不会编译,因为foo
实现错误:
class ConcreteFoo1 extends AbstractFoo {
foo: string; // type for "foo" isn't checked
}
But TS doesn't do any type-checking for optional members of IFoo
.但是 TS 不会对IFoo
可选成员进行任何类型检查。 Unless I implement it explicitly.除非我明确地实施它。 Then compiler will perform type-checking as expected:然后编译器将按预期执行类型检查:
class ConcreteFoo2 extends AbstractFoo implements IFoo {
foo(arg: number) { } // error when implementing IFoo explicitly
}
So my question is : Why typescript don't implicitly implement interface IFoo for concrete classes?所以我的问题是:为什么打字稿不为具体类隐式实现接口 IFoo? Is there some way to enforce this behavior?有没有办法强制执行这种行为?
If there's type error in how AbstractFoo
implements IFoo
, this results in error.如果AbstractFoo
实现IFoo
存在类型错误,则会导致错误。 IFoo
is not related to AbstractFoo
type and types that extend it in any other way. IFoo
与AbstractFoo
类型和以任何其他方式扩展它的类型无关。 It doesn't enforce foo
property type on its children because they are unaware of the fact that AbstractFoo
implements IFoo
.它不会对其子项强制foo
属性类型,因为他们不知道AbstractFoo
实现IFoo
的事实。
This is a way how IFoo
can affect children class:这是IFoo
如何影响儿童班级的一种方式:
class ConcreteFoo extends AbstractFoo implements IFoo {...}
If proper inheritance should be set up, this means that IFoo
should be a class, too:如果应该设置适当的继承,这意味着IFoo
应该是一个类:
abstract class AbstractFoo {
bar: number;
foo?: () => void;
}
abstract class BaseFoo extends AbstractFoo {
bar = 42;
};
class ConcreteFoo extends BaseFoo {...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.