所以我使用Visual Studio 2017模板“ASP.NET Core Web Application”和Angular创建了一个示例项目。
我将默认创建的package.json更新到了最新的模块版本。
运行npm install
命令并启动网站后,我遇到了与TypeScript相关的错误。
错误很明显。我做了一些研究,发现了TS 2.7的一个新特性: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html 严格类初始化 TypeScript 2.7引入了一个名为--strictPropertyInitialization的新标志。此标志执行检查以确保类的每个实例属性在构造函数体内或通过属性初始化器进行初始化。例如...[at-loader] ./ClientApp/app/components/fetchdata/fetchdata.component.ts:9:12出现错误 TS2564: 属性'forecasts'没有初始化程序,并且在构造函数中未被明确定义。
Angular正在开发模式下运行。调用enableProdMode()以启用生产模式。 client.js:67 [HMR]已连接 client.js:160 [HMR]捆绑包有1个错误 client.js:161 [at-loader] ./ClientApp/app/components/fetchdata/fetchdata.component.ts:9:12 TS2564: 属性'forecasts'没有初始化程序,并且在构造函数中未被明确定义。
这是出现错误的代码。
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;
}
这是我的tsconfig.json
文件。
{
"compilerOptions": {
"module": "es2015",
"moduleResolution": "node",
"target": "es5",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipDefaultLibCheck": true,
//"skipLibCheck": true, // Workaround for https://github.com/angular/angular/issues/17863. Remove this if you upgrade to a fixed version of Angular.
"strictPropertyInitialization": false,
"strict": false,
"lib": [ "es6", "dom" ],
"types": [ "webpack-env" ]
},
"exclude": [ "bin", "node_modules" ],
"atom": { "rewriteTsconfig": false }
}
然后,VS智能感知不会抱怨,但运行时仍然存在错误。
我还尝试使用public forecasts: WeatherForecast[];
定义forecasts
字段,但没有帮助。
Node v9.9.0 TypeScript 2.7.2 Angular 5.2.9
public forecasts?: WeatherForecast[]
。如果你在这个声明上悬停到forecast
上面,你会看到类型实际上是WeatherForecast[] | undefined
。 - Titian Cernicova-Dragomir