代码之家  ›  专栏  ›  技术社区  ›  Richard Simões

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

  •  0
  • Richard Simões  · 技术社区  · 4 年前

    基类:

    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指出显而易见的问题呢?还是我要以某种方式“撒谎”,歪曲他们之间的关系 Entity User ?

    0 回复  |  直到 4 年前
        1
  •  2
  •   spender    4 年前

    您可以创建一个类型来删除 can 基地的财产 Entity 键入,然后指定 实体 到该类型的变量。

    现在您可以创建一个从这个“class”引用变量派生的新类。

    这打破了多态性(正如最初的开发人员所做的那样)。太可怕了。别这样。咬紧牙关,重构你的烂摊子。

    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)
        }
    }
    
        2
  •  0
  •   Richard Simões    4 年前

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

    推荐文章