带有 nodejs 的 TypeScript:TypeScript 编译错误
TypeScript with nodejs: TypeScript compile Error
我正在使用带有 nodejs 的打字稿。在 tsconfig.json 文件中,我启用了“noImplicitAny”:true。我不想在我的代码中使用任何类型。到目前为止,我已经成功修复了所有错误。我留下了一个错误,我无法修复此错误。我正在使用 dotenv npm 包。我有这个 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
对于直接访问对象来说可能过于通用 - 您想要使用实际可用的键而不是任何可能的字符串。在 TypeScript 中,您可以这样做:
exports.get = function get(env: keyof typeof config) {
return config[env] || config.default
}
而且我相信它应该可以解决您的错误 + 为 env
参数启用正确的自动完成。
我正在使用带有 nodejs 的打字稿。在 tsconfig.json 文件中,我启用了“noImplicitAny”:true。我不想在我的代码中使用任何类型。到目前为止,我已经成功修复了所有错误。我留下了一个错误,我无法修复此错误。我正在使用 dotenv npm 包。我有这个 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
对于直接访问对象来说可能过于通用 - 您想要使用实际可用的键而不是任何可能的字符串。在 TypeScript 中,您可以这样做:
exports.get = function get(env: keyof typeof config) {
return config[env] || config.default
}
而且我相信它应该可以解决您的错误 + 为 env
参数启用正确的自动完成。