__env :-Element implicitly has an 'any' type because index expression is not of type 'number'

Viewed 179

I was trying to deploy angular node app on aws beanstalk by this blog https://blog.devgenius.io/deploy-angular-nodejs-application-to-aws-elastic-beanstalk-9ab13076a736

So initially I created the folder environments under the assets folder. Added env.js file to the environments folder and added the following code in there:

(function (window) {
   window.__env = window.__env || {};
   window.__env.SERVER_URL = 'http://localhost:3000';
}(this));

Then I added

 <script src=”/assets/environments/env.js”></script>

script to the index.html file.

I then added the following to environment.ts file and environment.prod.ts files:

server_URL: window['__env']['SERVER_URL']

I then got the following error with __env:

Element implicitly has an 'any' type because index expression is not of type 'number'.

enter image description here

2 Answers

TypeScript can use an implicit type for the window object. The default angular configuration will respect that type when building.

You can extend the window type by adding the following on top of the class to use your __env variable (I recommend you do this option):

declare global {
  interface YourWindow = Window & { '__env': any; }
}

...

server_URL: (window as YourWindow)['__env']['SERVER_URL']

You could also modify your tsconfig.json file to be more permissive:

{
  ...
  "suppressImplicitAnyIndexErrors": true
}

Using suppressImplicitAnyIndexErrors is quite a drastic approach. It is recommended to use a @ts-ignore comment instead:

export const environment = {
  production: false,
  // @ts-ignore
  server_URL: window["env"]["SERVER_URL"]
};
Related