英文:
Cypress - nested function instead of using while loop
问题
我注意到当我使用 while 循环时,Cypress 不起作用,所以我找到了这种解决方案:
const functionName = () => {
if (a != b) {
this.functionName();
} else {
cy.get(".selector").click();
}
};
这段代码(TypeScript)运行得非常好,但 'this' 会被标记为红色,并出现消息:"Object is possibly 'undefined'."
有没有办法消除这个错误?
英文:
I spotted that when I'm using while loop, cypress does not work, so instead of while loop I found this kind of solution:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const functionName = () => {
if ( a != b ) {
this.functionName();
} else {
cy.get(".selector").click()
}
};
<!-- end snippet -->
This block of code (typescript) works really well, but 'this' is highlighted in red and the message appears: "Object is possibly 'undefined'."
Any idea how can I to get rid off this error?
答案1
得分: 1
假设这是一个 TypeScript 错误,请添加[非空断言运算符](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator)
```ts
// 使用 --strictNullChecks 编译
function validateEntity(e?: Entity) {
// 如果 e 为 null 或无效实体,抛出异常
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // 断言 e 非空并访问 name
}
参考如何抑制“错误 TS2533:对象可能为'null'或'undefined'”回答了相同的问题。
你可能不需要 this.
前缀,因为该函数在当前作用域中定义(不是类方法)。
<details>
<summary>英文:</summary>
Assuming it's a typescript error, add the [Non-null assertion operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator)
```ts
// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
// Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}
For reference, How to suppress "error TS2533: Object is possibly 'null' or 'undefined'" answers the same question.
You probably don't need the this.
prefix at all, since the function is defined on the current scope (not a class method).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论