我正在使用 typescript 在 nodejs 中编程。
我正在使用 pdfmake 我为这个库安装了 typescript 定义文件 (@types/pdfmake)
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pdfmake/index.d.ts
我正在从该文件中导入枚举之一
从“pdfmake/build/pdfmake”导入 { PageSize };
并像这样使用 PageSize.A4
这可以编译,但是当我尝试访问这个枚举的值 A4 时,发生运行时错误
类型错误:无法读取未定义的属性“A4”
任何帮助将不胜感激
package.json:
{
"name": "nodejs-pdf-make",
"version": "1.0.0",
"description": "",
"main": "dist/app.js",
"scripts": {
"start": "tsc && node --inspect dist/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/express": "^4.17.1",
"tslint": "^5.19.0",
"typescript": "^3.6.2"
},
"dependencies": {
"@types/pdfmake": "^0.1.8",
"express": "^4.17.1",
"pdfmake": "^0.1.58"
}
}
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist"
},
"lib": ["es2015"]
}```
最佳答案
问题是类型定义只是针对类型。它们不会改变模块的运行时行为。因此,虽然 TypeScript 对您的代码很满意,因为类型定义表明此模块导出一个枚举 PageSize
,但在运行代码时这会分崩离析,因为实际上该模块不会导出 PageSize
.
我认为这是 @types/pdfmake
中的错误。
这个问题可以在 @types/pdfmake
中通过使枚举 const
来解决:
const enum PageSize {
// ...
}
TypeScript 自动内联 const 枚举。内联意味着编译器将 PageSize.A4
替换为 'A4'
,这样就不会在 JavaScript 代码中留下对 PageSize
的引用。
当然,这需要更改 @types/pdfmake
。我鼓励您在 DefinitelyTyped repo 上打开拉取请求或问题.
在 @types/pdfmake
中没有任何更改,您唯一的选择是使用硬编码字符串:
pageSize: 'A4' as PageSize
不幸的是,您甚至可能不得不将其转换为 PageSize
枚举,因为这是类型定义所期望的。
关于javascript - 如何使用 typescript 定义文件中的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57773414/