我正在嘗試遍歷字串陣列,以便對所有測驗使用相同的邏輯,但對于不同的設備大小。但是我不知道如何讓 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()
,即使它是一個字串,我也不會出錯。
uj5u.com熱心網友回復:
您可以明確告訴回呼dimension
是一個 ViewportPreset。
注意 types="cypress" 上的小 c 是約定,但在這里似乎無關緊要。
在型別中包含 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://www.uj5u.com/yidong/469959.html
下一篇:React創建元素道具未定義