TypeScript中的"Property has no initializer"错误:如何修复?
你好!我刚开始学习Angular和TypeScript,遇到了一个令人困惑的错误。我有一个简单的组件,在其中声明了一个`string`类型的属性`name`,但在编译时TypeScript报错:
```
Property 'name' has no initializer and is not definitely assigned in the constructor.
```
这是我的代码:
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html'
})
export class UserComponent {
name: string;
age: number;
constructor() {
// 我还没有赋值,计划稍后处理
}
setName(newName: string): void {
this.name = newName;
}
}
```
我明白TypeScript要求属性要么在声明时初始化,要么在constructor中初始化。但在我的情况下,我无法这样做——`name`的值将通过`setName()`方法从外部传入,该方法会在组件创建后调用。该怎么办?我是否必须写