在打字稿中的声明文件中扩展命名空间

时间:2019-06-09 06:35:57

标签: typescript

我正在尝试将命令添加到赛普拉斯名称空间中。我创建了一个commands.d.ts文件:

从'axe-core'导入{ElementContext,RunOptions}; 从'axe-core'导入{结果};

export type ViolationCallback = (violations: Result[]) => void;

declare namespace Cypress {
  interface Chainable<Subject = any> {
    checkA11yAndReportViolations(context?: ElementContext, options?: RunOptions): void;
    checkA11yLocal(context?: ElementContext, options?: RunOptions, violationCallback?: ViolationCallback): void;
  }
}

我的tsconfig.json如下:

{
  "compilerOptions": {
    "baseUrl": "../node_modules",
    "target": "es6",
    "isolatedModules": false,
    "module": "commonjs",
    "types": [
      "cypress",
      "node"
    ]
  },
  "include": [
    "integration/**/*.ts",
    "support/*.ts",
    "../node_modules/cypress"
  ]
}

我的commands.d.ts文件位于以上包含中引用的support文件夹中,但是当我尝试调用integration/spec.ts中的函数时:

cy.checkA11yAndReportViolations();

tsc抱怨:

  

属性'checkA11yAndReportViolations'在类型上不存在   “可束缚”。

1 个答案:

答案 0 :(得分:0)

对我来说很好,也许您忘记了实现界面

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "../node_modules",
    "target": "es6",
    "isolatedModules": false,
    "module": "commonjs",
    "types": [
      "cypress",
      "node"
    ]
  },
  "include": [
    "integration/**/*.ts",
    "support/*.ts",
    "../node_modules/cypress"
  ]
}

integration / spec.ts

import { Cypress } from '../support/commands'

export class Demo implements Cypress.Chainable {
  checkA11yAndReportViolations () {
    console.log('CALLED checkA11yAndReportViolations')
  }
  checkA11yLocal () {
    console.log('CALLED checkA11yLocal')
  }
}

support / commands.d.ts

import { ElementContext, RunOptions } from 'axe-core';
import { Result } from 'axe-core';

export type ViolationCallback = (violations: Result[]) => void;

declare namespace Cypress {
  interface Chainable<Subject = any> {
    checkA11yAndReportViolations(context?: ElementContext, options?: RunOptions): void;
    checkA11yLocal(context?: ElementContext, options?: RunOptions, violationCallback?: ViolationCallback): void;
  }
}

index.ts

import { Demo } from './integration/spec'

const d = new Demo()

d.checkA11yAndReportViolations()

结果

~/Documents/Dev/github/demo
❯ ts-node ./index.ts
CALLED checkA11yAndReportViolations