Skip to content

Commit b403efe

Browse files
authored
feat: make ability for cy.task to be type-safe
1 parent 813bd6b commit b403efe

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

cli/types/cypress.d.ts

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,20 @@
33
/// <reference path="./cypress-eventemitter.d.ts" />
44
/// <reference path="./cypress-type-helpers.d.ts" />
55

6+
type IsAny<X> =
7+
(<T>() => T extends X ? 1 : 2) extends
8+
(<T>() => T extends any ? 1 : 2) ? true : false;
9+
10+
type CypressConfig_Data = typeof import('../../../cypress.config')
11+
type AllTasks_CJS = CypressConfig_Data['CypressTasks']
12+
type AllTasks_ESM = CypressConfig_Data['default']['CypressTasks']
13+
14+
type AllTasks = IsAny<AllTasks_CJS> extends true ? AllTasks_ESM : AllTasks_CJS
15+
type TaskEventNames = keyof AllTasks & string
16+
17+
type MyParameter<T extends TaskEventNames> = Parameters<AllTasks[T]>[0]
18+
type MyReturnType<T extends TaskEventNames> = Awaited<ReturnType<AllTasks[T]>>
19+
620
declare namespace Cypress {
721
type FileContents = string | any[] | object
822
type HistoryDirection = 'back' | 'forward'
@@ -2164,7 +2178,23 @@ declare namespace Cypress {
21642178
*
21652179
* @see https://on.cypress.io/api/task
21662180
*/
2167-
task<S = unknown>(event: string, arg?: any, options?: Partial<Loggable & Timeoutable>): Chainable<S>
2181+
task<T extends TaskEventNames>(
2182+
event: T,
2183+
...myArgs: IsAny<AllTasks> extends true ?
2184+
[
2185+
arg?: any,
2186+
options?: Partial<Loggable & Timeoutable>
2187+
] : Parameters<AllTasks[T]>['length'] extends 0 ?
2188+
[
2189+
arg?: undefined,
2190+
options?: Partial<Loggable & Timeoutable>
2191+
] : [
2192+
arg: MyParameter<T>,
2193+
options?: Partial<Loggable & Timeoutable>
2194+
]
2195+
): Chainable<
2196+
IsAny<AllTasks> extends true ? unknown : MyReturnType<T>
2197+
>
21682198

21692199
/**
21702200
* Enables you to work with the subject yielded from the previous command.

0 commit comments

Comments
 (0)