After initializing a sample project using the Angular template in Visual Studio 2017, I made sure to update the package.json file with the latest module versions. However, upon executing the npm install
command and navigating to the site, an error related to TypeScript emerged.
ERROR in [at-loader] ./ClientApp/app/components/fetchdata/fetchdata.component.ts:9:12 TS2564: Property 'forecasts' has no initializer and is not definitely assigned in the constructor.
While Angular was operating in development mode, I attempted enabling production mode by calling enableProdMode(). Despite this effort, the error persisted.
The issue became apparent through further research. It appears that TypeScript 2.7 introduced a new feature regarding class initialization:
TypeScript 2.7 brings forth a flag known as --strictPropertyInitialization. This serves to ensure that each instance property of a class receives proper initialization within the constructor or via a property initializer.
The specific code segment triggering the error is as follows:
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'fetchdata',
templateUrl: './fetchdata.component.html'
})
export class FetchDataComponent {
public forecasts: WeatherForecast[];
constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
http.get(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
this.forecasts = result.json() as WeatherForecast[];
}, error => console.error(error));
}
}
interface WeatherForecast {
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
Furthermore, here's a glimpse of my tsconfig.json
configuration:
{
"compilerOptions": {
"module": "es2015",
"moduleResolution": "node",
"target": "es5",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipDefaultLibCheck": true,
"strictPropertyInitialization": false,
"strict": false,
"lib": [ "es6", "dom" ],
"types": [ "webpack-env" ]
},
"exclude": [ "bin", "node_modules" ],
"atom": { "rewriteTsconfig": false }
}
Despite trying various solutions like explicitly defining the forecasts
field as
public forecasts: WeatherForecast[];
, the error persists.
System specs at play during this conundrum: Node v9.9.0 TypeScript 2.7.2 Angular 5.2.9