0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I agree that string is too generic and I have used the exact code but still I am getting same error message. code that i have used: ` exports.get = function get(env: keyof typeof config) { return config[env] || config.default }`
Running it on TS playground worked for me: typescriptlang.org/play?#code/…
I'm not sure about the export syntax you're using, but if I change that, the function itself works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.