我正在使用 TypeScript develop
分支编译 two.d.ts
(可从 here 获得)。我收到以下错误:
Types of static property 'Utils' of class 'THREE.Shape' and class 'THREE.Path'
are incompatible
问题是
Shape
定义静态Utils
类Shape
间接继承于Curve
Curve
还定义了一个静态Utils
类,其签名与Shape.Utils
无关
根据语言规范,其格式不正确。总而言之,two.d.ts
包含类似以下代码的内容:
declare class A {
static Utils: {
f (): any;
}
}
declare class B extends A {
static Utils: {
// incompatible with A.Utils, without f(): any
g (): any;
}
}
抛开为什么静态成员的类型必须与同名继承的静态成员的类型兼容的问题 - 在其他几种 OO 语言中情况并非如此,但似乎确实如此在 TypeScript 中 - 我想知道如何修复 two.d.ts
以便我可以编译它。
我当前的解决方法只是将 Curve.Utils
的签名复制并粘贴到 Shape.Utils
中,以便后者在结构上扩展前者。但是,在 .d.ts
文件中捕获底层 two.js
文件 ( here ) 的签名的“正确”方法是什么?这是继承被错误使用的情况吗?
最佳答案
简短的回答是,根据规范,Typescript 不允许通过继承隐藏成员,例如 C# 会自动隐藏成员。
如 language specifications 中所定义第8.2.3节
A derived class inherits all members from its base class it doesn’t override. Inheritance means that a derived class implicitly contains all non-overridden members of the base class. Both public and private members are inherited, but only public members can be overridden. A member in a derived class is said to override a member in a base class when the derived class member has the same name and kind (instance or static) as the base class member. The type of an overriding member must be a subtype (section 3.8.2) of the type of the overridden member, or otherwise a compile-time error occurs.
和
Base class static members can be overridden by derived class static members of any kind as >long as the types are compatible, as described above.
也许他们在最新的编译器版本中添加了一些之前缺失的类型检查......
这是一个基于继承的建议解决方案:
declare class UtilsA{
f():any;
}
declare class UtilsB extends UtilsA{
g():any;
}
declare class A {
static Utils:UtilsA;
}
declare class B extends A {
static Utils:UtilsB;
}
关于static - Three.d.ts 中的静态属性与最新的 TypeScript 不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19605557/