Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Cypress error when getting variable as string

I'm migrating to using Typescript with Cypress but have an issue type casting aliases. I'm expecting a string but typescript is expecting JQuery<HTMLElement>.

Example:

cy.wrap("a string").as("myString")

cy.get("@myString").then( myString => {
   console.log(typeof myString) // => "string"
})

I checked the typescript definitions for cy.get and found:

get<E extends Node = HTMLElement>(selector: string, options?: Partial<Loggable & Timeoutable & Withinable & Shadow>): Chainable<JQuery<E>>
// AND
get<E extends Node = HTMLElement>(selector: string, options?: Partial<Loggable & Timeoutable & Withinable & Shadow>): Chainable<JQuery<E>>

At the moment, I'm getting the following error:

Argument of type '(myString: string) => string' is not assignable to parameter of type '(this: ObjectLike, currentSubject: JQuery<HTMLElement>) => void'.
      Types of parameters 'myString' and 'currentSubject' are incompatible.
        Type 'JQuery<HTMLElement>' is not assignable to type 'string'.

How can I fix this error?

Thanks.

like image 938
denislexic Avatar asked May 11 '26 13:05

denislexic


1 Answers

You can specify the output in the following manner:

cy.get<string>("@myString").then( myString => {
   // Do something here
})
like image 176
denislexic Avatar answered May 14 '26 08:05

denislexic