将变量作为字符串获取时出现 Typescript Cypress 错误

Typescript Cypress error when getting variable as string

我正在迁移到将 Typescript 与 Cypress 结合使用,但在类型转换别名时遇到问题。我期待 string 但打字稿期待 JQuery<HTMLElement>.

示例:

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

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

我检查了 cy.get 的打字稿定义并发现:

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

目前,我收到以下错误:

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

我该如何解决这个错误?

谢谢。

您可以通过以下方式指定输出:

cy.get<string>("@myString").then( myString => {
   // Do something here
})