Angular中属性未在构造函数定义引发TypeScript 2564错误
解决Angular组件中TypeScript 2564错误(未初始化属性)
我在项目中使用Google Maps API编写Angular组件时,遇到了TypeScript未定义错误,组件代码如下:
export class AppComponent { startLocation: string; endLocation: string; maneuvers: any[]; constructor(private mapQuestService: MapQuestService) {} getDirections() { this.mapQuestService.getDirections(this.startLocation, this.endLocation).subscribe(data => { this.maneuvers = data.route.legs[0].maneuvers; }); } }
对应的TS 2564错误信息如下:
[{ "resource": "/c:/xampp/htdocs/CS701/hw5-part1/src/app/app.component.ts", "owner": "typescript", "code": "2564", "severity": 8, "message": "Property 'startLocation' has no initializer and is not definitely assigned in the constructor.", "source": "ts", "startLineNumber": 10, "startColumn": 3, "endLineNumber": 10, "endColumn": 16 },{ "resource": "/c:/xampp/htdocs/CS701/hw5-part1/src/app/app.component.ts", "owner": "typescript", "code": "2564", "severity": 8, "message": "Property 'endLocation' has no initializer and is not definitely assigned in the constructor.", "source": "ts", "startLineNumber": 11, "startColumn": 3, "endLineNumber": 11, "endColumn": 14 },{ "resource": "/c:/xampp/htdocs/CS701/hw5-part1/src/app/app.component.ts", "owner": "typescript", "code": "2564", "severity": 8, "message": "Property 'maneuvers' has no initializer and is not definitely assigned in the constructor.", "source": "ts", "startLineNumber": 12, "startColumn": 3, "endLineNumber": 12, "endColumn": 12 }]
疑问:不清楚除了app.component.ts外还需要在哪里定义这些属性,求解决方法。
解决方法
这些属性只需要在app.component.ts的类中定义,错误原因是TypeScript严格模式要求类属性必须明确初始化(声明时赋值或构造函数中赋值),以下是三种可行方案:
方案1:声明时直接初始化
给属性设置初始值,满足TypeScript的严格检查要求:
export class AppComponent { startLocation: string = ''; endLocation: string = ''; maneuvers: any[] = []; constructor(private mapQuestService: MapQuestService) {} getDirections() { this.mapQuestService.getDirections(this.startLocation, this.endLocation).subscribe(data => { this.maneuvers = data.route.legs[0].maneuvers; }); } }
方案2:构造函数中初始化
如果需要在构造阶段做逻辑处理,可以在constructor中给属性赋值:
export class AppComponent { startLocation: string; endLocation: string; maneuvers: any[]; constructor(private mapQuestService: MapQuestService) { this.startLocation = ''; this.endLocation = ''; this.maneuvers = []; } getDirections() { this.mapQuestService.getDirections(this.startLocation, this.endLocation).subscribe(data => { this.maneuvers = data.route.legs[0].maneuvers; }); } }
方案3:关闭严格属性检查(不推荐)
如果暂时不想修改代码,可以在项目根目录的tsconfig.json中关闭strictPropertyInitialization检查,但这会降低TypeScript的类型安全性,不建议长期使用:
{ "compilerOptions": { // 其他配置... "strictPropertyInitialization": false } }
内容的提问来源于stack exchange,提问作者GPT Gabriel Patrick Thomas
相关产品推荐
相关产品推荐

