我试图循环一个字符串数组,以便在所有测试中使用相同的逻辑,但对不同的设备大小使用相同的逻辑。但是,我不知道如何使TypeScript对“ViewportPreset”的类型感到高兴。下面是测试文件的外观:
/// <reference types="Cypress" />
const dimensions = ["iphone-xr", "samsung-s10"];
context("check responsiveness", () => {
dimensions.forEach((dimension) => {
it("check responsiveness", () => {
cy.viewport(dimension); // <- error
});
});
});我得到的错误:Argument of type 'string' is not assignable to parameter of type 'ViewportPreset'.ts(2345)。我试着做一些类似const dimensions : ViewportPreset[] = ["iphone-xr", "samsung-s10"];的事情,但是它用Cannot find name 'ViewportPreset'.ts(2304)来响应。我目前唯一的解决方案是使用any[],但我认为通常应该避免使用any,因为它首先消除了TypeScript的所有优点。另外,如果我手动将其中一个维度添加到cy.viewport()中,即使它是一个字符串,也不会出现错误。
发布于 2022-05-08 04:17:26
您可以显式地告诉回调,dimension是一个ViewportPreset。
注意,types=上的小c++“cypress”是惯例,但在这里它似乎并不重要。
在类型中包括Cypress命名空间。
/// <reference types="cypress" />
context("check responsiveness", () => {
dimensions.forEach((dimension: Cypress.ViewportPreset) => {
it("check responsiveness", () => {
cy.viewport(dimension);
});
});
})
...此外,这是有效的(而不是上面)
const dimensions: Cypress.ViewportPreset[] = ['iphone-6', 'ipad-2']https://stackoverflow.com/questions/72157523
复制相似问题