Akxe
Akxe

Reputation: 11495

Extend typescript function into callable object

I would like to extend Mocha's describe with forUsers function that would create multiple describe. One for each user.

Original description definition:

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;
}

My extension:

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
        }
    }
}

But I am getting this error:

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; }'.

That only, can be only of type original type, even if the new type includes the old one.

Upvotes: 0

Views: 448

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30919

Right, if a property has a hard-coded type (as opposed to an interface that you can augment), you can't change the type. If you really want to change the type of only, rather than redesign your API extension in a way that can be declared via augmentation, then you'll need to fork the Mocha type declarations; see this answer for the possible ways to do that.

Upvotes: 1

Related Questions