1

On an Angular 12 application I have the following environment:

export const environment = {
  production: false,
  applications: [
    { name: "Api", url: "https://localhost:5001" },
    { name: "Bot", url: "https://localhost:5003"}
  ],
}

And I create an Application interface and EnvironmentService class:

export interface Application {
  name: string;
  url: string;
}

export class EnvironmentService {

  constructor() {}

  get production() : boolean { return environment.production; }

  get applications() : Application[] { return environment.applications };

}

But I get an error:

Type '{ name: string; url: string; }[]' is not assignable to type 'Application[]'.

How can I convert environment.applications to Application[]?

1
  • There is no JSON in this question. Commented Jun 10, 2021 at 20:04

1 Answer 1

1

Personaly i also describe my environment constant via interface. That way i can be sure that the constants for thedifferent environments will follow the same structure.

Therefore i would write it like:

export interface Application {
  name: string;
  url: string;
}

interface Environment {
  production: boolean;
  applications: Application[];
}

export const environment: Environment = {
  production: false,
  applications: [
    { name: "Api", url: "https://localhost:5001" },
    { name: "Bot", url: "https://localhost:5003"}
  ],
}

export class EnvironmentService {
  constructor() {}
  get production() : boolean { return environment.production; }
  get applications() : Application[] { return environment.applications };
}

With hard typing and no implicite "any", the IDE can give you all the help that you need. Omiting a type is less work, and in rare occurances the code may be even more readable, but its also a lot easier to make mistakes.

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

Comments

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.