【问题标题】:Extend typescript function into callable object将打字稿功能扩展到可调用对象
【发布时间】:2019-03-14 07:27:39
【问题描述】:

我想扩展 Mocha 的 describeforUsers 函数,这将创建多个描述。每个用户一个。

原始描述定义:

interface IContextDefinition {
    (description: string, callback: (this: ISuiteCallbackContext) => void): ISuite;
    only(description: string, callback: (this: ISuiteCallbackContext) => void): ISuite;
    skip(description: string, callback: (this: ISuiteCallbackContext) => void): void;
    timeout(ms: number): void;
}

我的扩展:

declare namespace Mocha {
    interface IContextDefinition {
        forUsers(description: string, users: userType[], callback: (this: ISuiteCallbackContext, user: Cypress.userType) => void): void
        only: {
            (description: string, callback: (this: ISuiteCallbackContext) => void): ISuite
            forUsers(description: string, users: userType[], callback: (this: ISuiteCallbackContext, user: userType) => void): void
        }
        skip: {
            (description: string, callback: (this: ISuiteCallbackContext) => void): ISuite
            forUsers(description: string, users: userType[], callback: (this: ISuiteCallbackContext, user: userType) => void): void
        }
    }
}

但我收到此错误:

Subsequent property declarations must have the same type.  Property 'only' must be of type '(description: string, callback: (this: ISuiteCallbackContext) => void) => ISuite', but here has type '{ (description: string, callback: (this: ISuiteCallbackContext) => void): ISuite; forUsers(description: string, users: userType[], callback: (this: ISuiteCallbackContext, user: userType) => void): void; }'.

那个only,只能是原始类型,即使新类型包含旧类型。

【问题讨论】:

  • 你为什么要覆盖定义?如果您只是在命名空间中定义自己的定义,我认为会更好
  • 文件是有作用域的,这意味着,除非导出,否则变量不会共享,并且由于我不希望其他人导入此函数,因此声明 describe.forUsers 听起来是最好的地方。

标签: typescript interface extending


【解决方案1】:

是的,如果属性具有硬编码类型(与可以扩充的接口相反),则无法更改类型。如果您真的想更改only 的类型,而不是重新设计您的API 扩展以通过扩充来声明,那么您需要分叉Mocha 类型声明;请参阅this answer 了解可能的方法。

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 2022-01-11
    • 2014-10-06
    相关资源
    最近更新 更多