[英]Typescript: class implements interface issue?
In Typescript 2.5.2 following does not work:在 Typescript 2.5.2 以下不起作用:
interface I {
m?():void;
}
class C implements I {
}
let c = new C();
c.m(); <== Error : TS2339:Property 'm' does not exist on type 'C'.
Why is the m
method not found?为什么找不到m
方法?
If I add:如果我添加:
interface C extends I {}
It's ok!没关系! Or if I add:或者,如果我添加:
let c = new C() as C & I;
It's ok too.也没关系。
As I understand implements
should combine C
and I
types as C & I. Is it an issue?据我所知, implements
应该将C
和I
类型组合为 C & I。这是一个问题吗?
The interface you have is a weak type that doesn't enforce the property m
on implementers.您拥有的接口是一个弱类型,它不会对实现者强制执行属性m
。
TypeScript is smart enough to see that m
is definitely not on your class, but you can prevent the error by asking TypeScript to treat the variable as the interface: TypeScript 足够聪明,可以看到m
绝对不在您的类中,但是您可以通过要求 TypeScript 将变量视为接口来防止错误:
let c: I = new C();
c.m();
Despite this trick, you'll still have a runtime problem, which TypeScript tried to warn you about.尽管有这个技巧,您仍然会遇到运行时问题,TypeScript 试图警告您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.