TypeScript Reference ยท Error Codes Worth Knowing
TypeScript error TS2564: property has no initializer
TS2564 in TypeScript means a class property is not definitely assigned in the constructor. See why it appears under strict and the four ways to fix it.
TS2564 reads Property 'name' has no initializer and is not definitely assigned in the constructor. It is reported for class fields whose type does not include undefined when the compiler cannot see a value being assigned on every path through the constructor. It comes from strictPropertyInitialization, which is part of strict and requires strictNullChecks.
The check protects you from objects whose field is read before it was ever set. At runtime such a field would simply be undefined, even though the type says string.
class User { name: string; // error TS2564 if nothing assigns it }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
The error appears once per uninitialised field. The fixes:
| Fix | When to use it |
|---|---|
Assign in the constructor (including a parameter property such as constructor(public name: string)) |
The value is known at construction. Best choice. |
Initialize inline: role = "reader" |
There is a sensible default. |
Make the type honest: email?: string or string | undefined |
The value really may be absent. |
Definite assignment assertion: age!: number |
A framework or init() method sets it before use; you vouch for it. |
Usage notes
- Constructor paths are analysed. If the constructor assigns the field in only one branch of an
if, the error remains. Assign on every path or give a default. - Assignments inside helper methods do not count. The compiler only sees direct assignments in the constructor, so calling
this.setup()does not satisfy the check. !:removes the safety net. It is erased at runtime. If the field is read before assignment you getundefinedwith astringtype. Use it for dependency injection, ORMs or lifecycle hooks, not to silence the compiler.- Subclass fields with
declare. To narrow a base-class field without re-emitting it, writedeclare name: string;. - Not reported for fields typed
any,unknown, or any type containingundefined. - Turning the flag off hides the error but not the bug. Consider fixing the model instead.