对于具有Typescript不兼容继承实践的JS库,我应该如何填写模块声明文件



我正在填写第三方JS库的模块声明,该库包含子类,这些子类(根据Typescript的估计(不兼容地覆盖父类的方法。这种情况有很多,但一个简单的例子如下:

基本类别:

class Entity {
...
/**
* Test whether a given User has permission to perform some action on this Entity
* @param {User} user           The User requesting creation
* @param {string} action       The attempted action
* @return {boolean}            Does the User have permission?
*/
can(user, action) {
...
}
}

子类:

class User extends Entity {
...
/**
* Test whether the User is able to perform a certain permission action. Game Master users are always allowed to
* perform every action, regardless of permissions.
*
* @param {string} permission     The action to test
* @return {boolean}              Does the user have the ability to perform this action?
*/
can(permission) {
...
}
}

在没有tsc指出显而易见的地方的情况下,我如何忠实地表示像上面这样的重写方法?或者我将不得不";谎言;以某种方式歪曲CCD_ 1和CCD_?

您可以创建一个从基本Entity类型中删除can属性的类型,然后将Entity分配给该类型的变量。

现在您可以创建一个派生自这个"的新类;类"-引用变量。

这打破了多态性(就像最初的开发人员一样(。太可怕了。不要这样做。咬紧牙关,重构你的烂摊子。

class Entity {
can(user: string, action: string) {
console.log(user, action)
}
}
type PartialEntity = new () => { [P in Exclude<keyof Entity, 'can'>]: Entity[P] }
const EntityNoCan: PartialEntity = Entity;
class User extends EntityNoCan {
can(permission: number) {
console.log(permission)
}
}

似乎// @ts-ignore实际上是这里唯一的选项。另一个建议的解决方案不适用于类型声明。

最新更新