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[]
?
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.