[英]TypeScript with nodejs: TypeScript compile Error
我在 nodejs 中使用 typescript。 在 tsconfig.json 文件中,我启用了“noImplicitAny”:true。 我不想在我的代码中使用任何类型。 到目前为止,我已经成功修复了所有错误。 我留下了一个错误,我无法修复此错误。 我正在使用 dotenv npm package。我有这个 config.ts 文件,我在其中指定了环境变量,并且收到了以下错误消息。
我在我的终端中收到此错误:
config.ts(13,12): error TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ production: { SECRET: string | undefined; DATABASE: string | undefined; }; default: { SECRET: string; DATABASE: string; }; }'.
config.ts 文件中的代码:
const config = {
production: {
SECRET: process.env.SECRET,
DATABASE: process.env.MONGODB_URI
},
default: {
SECRET: 'mysecretkey',
DATABASE: 'mongodb://localhost:27017/pi-db'
}
}
exports.get = function get(env: any[string]) {
return config[env] || config.default
}
我试图将 env 设置为字符串,但我仍然收到相同的错误消息。
exports.get = function get(env: string) {
return config[env]: string || config.default: string
}
在过去的几天里,我试图摆脱这个错误。 我是 TypeScript 的新用户。
string
对于直接访问 object 来说可能太通用了——你想使用实际可用的键而不是任何可能的字符串。 在TypeScript中,可以这样做:
exports.get = function get(env: keyof typeof config) {
return config[env] || config.default
}
而且我相信它应该解决您的错误+为env
参数启用正确的自动完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.