In the first example, myString has ts 2322 error because it believes returnedString is a number (it is not). In the second example, if we explicitly return getNumber(), there is no ts 2322 error.
getString() returns a value within it's definition. Cypress will consider the current subject as the one who was last returned or explicitly returned in the callback of a method chain, which in this case is myString()
How can I address this error without using 'return' keyword? I would like to use the style of example 1 but don't want false positive syntax highlighting
describe('example with error', () => {
it('example with error', () => {
getNumber()
.then((returnedNumber) => {
getString()
})
.then((returnedString) => {
const myString: string = returnedString // <-- HERE: "Type 'number' is not assignable to type 'string'. ts(2322)"
expect(myString).to.equal('string') // true
})
})
it('example without error', () => {
getNumber()
.then((returnedNumber) => {
return getString() // <-- HERE: explicitly returning
})
.then((returnedString) => {
const myString: string = returnedString
expect(myString).to.equal('string') // true
})
})
})
function getNumber(): Cypress.Chainable<number> {
return cy.wrap(1)
}
function getString(): Cypress.Chainable<string> {
return cy.wrap('string')
}
From the docs for .then()
Whatever is returned from the callback function becomes the new subject and will flow into the next command (with the exception of undefined)
Additionally, the result of the last Cypress command in the callback function will be yielded as the new subject and flow into the next command if there is no return.
I'm not sure how you can define that behaviour (switching subject if no explicit return) to the Typescript compiler.
But to me the implication is that Subject can have type any.
Typing the parameter as such removes the error message
getNumber()
.then(() => {
getString() // Typescript can't infer Subject will be string
// just because there's no return
})
.then((returnedString: any) => {
const myString: string = returnedString // no error
})