我正在使用Window
字段扩展dataLayer
界面:
// ./src/@types/Window.d.ts
interface Window {
dataLayer: {
push: (...args) => void
}
}
我的测试文件包含:
// ./src/__tests__/index.test.ts
describe('window', () => {
it("window object should not be null", () => {
window.dataLayer.push('hello') // just for demonstrating the type error
expect(window).not.eq(null)
});
})
当我使用package.json
中的此命令运行mocha时,收到关于dataLayer
的打字稿编译类型错误:
mocha --timeout 3000 -r ts-node/register src/**/*.test.ts
输出:
.../node_modules/ts-node/src/index.ts:228
return new TSError(diagnosticText,diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
sr/__tests__/index.test.ts(26,12): error TS2339: Property'dataLayer' does not exist on type 'Window'.
我的./tsconfig.json
包含:
{
"compilerOptions": {
"outDir": "./dist",
"sourceMap": true,
"noImplicitAny": false,
"module": "commonjs",
"target": "es6",
"jsx": "react",
"declaration": true,
"allowJs": false,
"allowSyntheticDefaultImports": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"esModuleInterop": true,
"downlevelIteration": true,
"lib": ["es5", "es2015", "dom", "scripthost"],
"typeRoots": ["node_modules/@types", "src/@types"]
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
看来打字稿只是忽略了我的typeRoots
文件中的tsconfig
声明。
如何在TypeScript和Mocha中正确使用自己的类型减速度?