Property has no initializer and is not definitely assigned in the constructor
Ошибка "Свойство не имеет инициализатора и не определено в конструкторе" возникает, когда мы объявляем свойство класса без его инициализации.
Чтобы исправить ошибку, предоставьте начальное значение для свойства класса или используйте non-null assertion.
class Employee {
// ⛔️ Error: Property 'name' has no initializer
// and is not definitely assigned in the constructor.ts(2564)
name: string;
salary: number;
tasks: string[];
}
Мы объявили в классе свойства определенного типа, но не задали им начальные значения.
Укажите начальные значения для свойств класса:
class Employee {
name = 'Bobby Hadz';
salary = 0;
tasks: string[] = [];
address: { country: string; city: string } = {
country: '',
city: '',
};
}
Использовать non-null assertion operator:
class Employee {
name!: string;
salary!: number;
tasks!: string[];
}
Указать значения свойств в конструкторе:
class Employee {
name: string;
salary: number;
tasks: string[];
constructor() {
this.name = '';
this.salary = 0;
this.tasks = [];
}
}
Сделать свойства необязательными
class Employee {
name?: string;
salary?: number;
tasks?: string[];
}
Отключение проверки типа для инициализации свойства
tsconfig.json
{
"compilerOptions": {
// ... rest
"strict": true, // 👈️ if you have this
"strictPropertyInitialization": false // 👈️ add this below
}
}
