我有一个 TypeScript 项目,其脚本如下所示:
class MyClass {
constructor(a?: number) { /* ... */ }
}
const x = new MyClass(process.env.MY_VARIABLE);
为了启用环境变量的自动完成和类型支持,我创建了一个
env.d.ts
文件,如下所示:
declare global {
namespace NodeJS {
interface ProcessEnv {
MY_VARIABLE: number;
}
}
}
export {};
当我使用以下命令运行脚本时,一切正常:
tsc -p . && node -r dotenv/config dist/main.js
现在我想使用 nodemon 运行相同的脚本,以便在进行更改时自动重新启动。这是我尝试过的命令:
nodemon -r dotenv/config src/main.ts
执行命令时,出现以下错误:
src/main.ts:12:3 - error TS2322: Type 'string | undefined' is not assignable to type 'number | undefined'.
Type 'string' is not assignable to type 'number'.
有办法解决这个问题吗?
我尝试将此行添加到我的
main.ts
:
import 'dotenv/config';
还尝试使用
运行脚本ts-node src/main.ts
但还是出现错误。
process.env
是 Record<string, string>
,它不能有 number
值。
将您的
MY_VARIABLE:
输入为 string
并使用 new MyClass(+(process.env.MY_VARIABLE ?? 0));
(矿石 new MyClass(Number(process.env.MY_VARIABLE ?? 0));
)(或 constructor(a?: string)
)