Skip to content

Commit

Permalink
fix: type for Command.add with apending subject argument (cypress-io#…
Browse files Browse the repository at this point in the history
  • Loading branch information
SimeonC committed Nov 25, 2021
1 parent 71d92e0 commit 4a48ab3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
13 changes: 12 additions & 1 deletion cli/types/cypress.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,17 @@ declare namespace Cypress {
*/
type Config = ResolvedConfigOptions & RuntimeConfigOptions

type AddSubjectArgument<
TPrevSubject extends CommandOptions['prevSubject'],
TFunction extends (...args: any[]) => any
> = (
...args: [
TPrevSubject extends 'element' ? JQuery | HTMLElement
: TPrevSubject extends 'window' ? Window
: TPrevSubject extends 'document' ? Document
: TPrevSubject extends true ? NonNullable<any> : any, ...Parameters<TFunction>]
) => ReturnType<TFunction>

/**
* Several libraries are bundled with Cypress by default.
*
Expand Down Expand Up @@ -421,7 +432,7 @@ declare namespace Cypress {
*/
Commands: {
add<T extends keyof Chainable>(name: T, fn: Chainable[T]): void
add<T extends keyof Chainable>(name: T, options: CommandOptions, fn: Chainable[T]): void
add<T extends keyof Chainable, TOptions extends CommandOptions>(name: T, options: TOptions, fn: Chainable[T] extends (...args: any[]) => any ? TOptions['prevSubject'] extends false ? Chainable[T] : AddSubjectArgument<TOptions['prevSubject'], Chainable[T]> : never): void
overwrite<T extends keyof Chainable>(name: T, fn: Chainable[T]): void
}

Expand Down
32 changes: 31 additions & 1 deletion cli/types/tests/cypress-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,37 @@ namespace CypressCommandsTests {
arg
return
})
Cypress.Commands.add('newCommand', { prevSubject: true }, (arg) => {
Cypress.Commands.add('newCommand', { prevSubject: true }, (subject, arg) => {
// $ExpectType NonNullable<any>
subject
// $ExpectType string
arg
return
})
Cypress.Commands.add('newCommand', { prevSubject: 'element' }, (subject, arg) => {
// $ExpectType HTMLElement | JQuery<HTMLElement>
subject
// $ExpectType string
arg
return
})
Cypress.Commands.add('newCommand', { prevSubject: 'window' }, (subject, arg) => {
// $ExpectType Window
subject
// $ExpectType string
arg
return
})
Cypress.Commands.add('newCommand', { prevSubject: 'document' }, (subject, arg) => {
// $ExpectType Document
subject
// $ExpectType string
arg
return
})
Cypress.Commands.add('newCommand', { prevSubject: 'optional' }, (subject, arg) => {
// $ExpectType any
subject
// $ExpectType string
arg
return
Expand Down

0 comments on commit 4a48ab3

Please sign in to comment.