Home > Back-end >  TypeScript with nodejs: TypeScript compile Error
TypeScript with nodejs: TypeScript compile Error

Time:05-24

I am using typescript with nodejs. In the tsconfig.json file, I have enabled "noImplicitAny": true. I do not want to use the any type in my code. I have successfully fixed all the errors I have have got so far. I am left one error and I am not able to fix this error. I am using dotenv npm package. I have this config.ts file where I specify the environment variables and I am getting the follow error message.

I am getting this error in my terminal:

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; }; }'.

Code in the config.ts file:

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
}

I have tried to make the env as string, but I am still getting the same error message.

exports.get = function get(env: string) {
    return config[env]: string || config.default: string
}

I am trying to get rid of this error for the last couple of days. I am new with TypeScript.

CodePudding user response:

string might be too generic for directly accessing an object - you want to use the actual available keys and not any possible string. In TypeScript, you can do this:

exports.get = function get(env: keyof typeof config) {
    return config[env] || config.default
}

And I believe it should solve your error enable proper auto completion for the env argument.

CodePudding user response:

set env as a string:

exports.get = function get(env: string)
  • Related