将打字稿功能扩展到可调用对象

时间:2018-10-09 13:32:53

标签: typescript interface extending

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

原始描述定义:

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的类型也只能是原始类型。

1 个答案:

答案 0 :(得分:1)

对,如果属性具有硬编码类型(与您可以扩展的接口相对),则不能更改类型。如果您确实想更改only的类型,而不是通过可以通过扩充声明的方式重新设计API扩展,则需要派生Mocha类型声明;请参见this answer,了解实现此操作的可能方法。