我正在閱讀這篇關于賽普拉斯的文章。最后一部分,作者在呼叫時重寫了typescript要推斷的型別Cypress.env。
這是我想了解的片段。
export { };
declare global {
namespace Cypress {
export interface Cypress {
/**
* Returns all environment variables set with CYPRESS_ prefix or in "env" object in "cypress.json"
*
* @see https://on.cypress.io/env
*/
env(): Partial<EnvKeys>;
/**
* Returns specific environment variable or undefined
* @see https://on.cypress.io/env
* @example
* // cypress.json
* { "env": { "foo": "bar" } }
* Cypress.env("foo") // => bar
*/
env<T extends keyof EnvKeys>(key: T): EnvKeys[T];
/**
* Set value for a variable.
* Any value you change will be permanently changed for the remainder of your tests.
* @see https://on.cypress.io/env
* @example
* Cypress.env("host", "http://server.dev.local")
*/
env<T extends keyof EnvKeys>(key: T, value: EnvKeys[T]): void;
/**
* Set values for multiple variables at once. Values are merged with existing values.
* @see https://on.cypress.io/env
* @example
* Cypress.env({ host: "http://server.dev.local", foo: "foo" })
*/
env(object: Partial<EnvKeys>): void;
}
}
}
interface EnvKeys {
'boards': Array<{
created: string;
id: number;
name: string;
starred: boolean;
user: number;
}>;
'lists': Array<{
boardId: number
title: string
id: number
created: string
}>;
}
我在這個片段中有幾個問題:
- 當它被命名為時,打字稿如何知道這個檔案
env.d.ts?我知道如果檔案與檔案命名相同,打字稿會自動知道型別(例如command.ts->command.d.ts - 這里有什么用
export {}。如果我將此注釋掉,Vscode 會抱怨。 declare global當原始賽普拉斯打字稿以 開頭時,為什么我們必須在此處添加declare namespace Cypress?
uj5u.com熱心網友回復:
我不是打字稿專家,但這是我的看法
1. typescript 命名為 env.d.ts 時如何知道這個檔案
在tsconfig.json你有
include": [
"**/*.ts"
]
這意味著env.d.ts包含在編譯中。
運行tsc --listFiles --noEmit以查看包含的內容。
2.這里的export {}有什么用
您正在合并命名空間,檔案Merging Namespaces說
為了合并命名空間,來自在每個命名空間中宣告的匯出介面的型別定義本身會被合并。
進一步
非匯出成員僅在原始(未合并)命名空間中可見。這意味著合并后,來自其他宣告的合并成員看不到非匯出成員。
所以,它是資訊隱藏——比如公共變數和私有變數。
哎呀,錯誤的答案
我剛剛意識到你想知道第一行。
請參閱此答案
全域范圍的增強只能直接嵌套在外部模塊或環境模塊宣告中(2669)
我認為訣竅在于“外部模塊”是一個包含匯入或匯出陳述句的檔案,因此這使其成為“外部模塊”。
3. 為什么一定要加上declare global
Ref全域增強
您還可以從模塊內部向全域范圍添加宣告
當你撰寫一個測驗時,你可以使用Cypress.Commands.add(), cy.get(),it()等而不需要匯入任何東西,因為它們是全域宣告的。
要與全域賽普拉斯介面合并,您的增強功能還必須宣告為全域。
要查看效果,請更改env.d.ts
declare module "env" {
namespace Cypress {
和addTaskApi.ts
Cypress.Commands.add('addTaskApi', ({ title, boardIndex = 0, listIndex = 0 }) => {
cy.request('POST', '/api/tasks', {
title,
boardId: Cypress.env('boards')[boardIndex].id,
listId: Cypress.env('lists')[listIndex].id
})
.then(({ body }) => {
const tasks = Cypress.env('tasks') // tasks typed as any
// instead of 'tasks': Array<{ boardId:...number;
tasks.push(body);
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450800.html
