[英]How to use enum from typescript definition file?
我正在使用typescript在nodejs中编程。
我正在使用pdfmake,并且为此库安装了打字稿定义文件(@ types / pdfmake)
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pdfmake/index.d.ts
我正在从此文件导入一个枚举
import { PageSize } from "pdfmake/build/pdfmake";
并像这样使用它PageSize.A4
这样可以编译,但是当我尝试访问该枚举的值A4时,会发生运行时错误
TypeError:无法读取未定义的属性“ 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
的错误。
通过使枚举const
可以在@types/pdfmake
解决此问题:
const enum PageSize {
// ...
}
TypeScript自动内联const枚举。 内联意味着编译器用'A4'
替换PageSize.A4
,以便在JavaScript代码中没有对PageSize
引用。
当然,这需要更改@types/pdfmake
。 我建议您在DefinitelyTyped仓库中打开拉取请求或发布。
在@types/pdfmake
不做任何更改,您唯一的选择是使用硬编码字符串:
pageSize: 'A4' as PageSize
不幸的是,您甚至可能必须将其PageSize
转换为PageSize
枚举,因为这是类型定义所期望的。
首先,您的导入不正确,因为pdfmake / build / pdfmake没有默认导出。 您可以使用:
import * as pdfMake from "pdfmake/build/pdfmake";
以获得对模块的引用,但是您会发现该模块没有对PageSize枚举的引用,因为它没有像Burt_Harris在其答案中解释的那样被导出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.