Error "Property has no initializer" in TypeScript: how to fix?
Hello everyone! I'm a beginner in TypeScript and Angular, and I've encountered a very strange error. I have a component where I declare a property, but TypeScript complains that it is not initialized. Here is my code:
```typescript
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-user',
template: `
`
})
export class UserComponent {
@Input() user: User;
public userName: string;
private id: number;
constructor() {
// Do nothing in the constructor
}
ngOnInit() {
this.userName = this.user.name;
this.id = this.user.id;
}
}
```
When compiling, I get errors:
- `Property 'user' has no initializer and is not definitely assigned in the constructor.`
- `Property 'userName' has no initializer and is not definitely assigned in the constructor.`
- `Property 'id' has no initializer and is not definitely assigned in the constructor.`
How can I fix this? I thought that if I use `@Input()`, the property will be initialized from the parent component. And `userName` and `id` are initialized in `ngOnInit()`. Why does TypeScript require initialization in the constructor? What is the correct way to handle this?
{{ user.name }}
{{ user.email }}
No answers yet.
Log in to leave an answer
Blogs