Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript TS2564: Property has no initializer and is not definitely assigned

TS2564 means the compiler can't prove a field is assigned before the constructor ends. Defaults, definite assignment and optional fields each fit one case.

~5 min readTypeScript
#typescript#ts2564#strict-mode#tsconfig
Bold white headline reading TS2564 NO INITIALIZER with a TypeScript class crate holding an empty amber field slot on the right.

Introduction & Quick Summary

The first tsc --noEmit after switching a project to strict prints this wall of errors:

code
src/domain/user.ts:5:3 - error TS2564: Property 'email' has no initializer and is not definitely assigned in the constructor. 5 email: string; ~~~~~

Quick answer: pick one honest option per field instead of turning the flag off.

ts
class User { email = ""; // 1. a real default value id!: string; // 2. assigned outside the constructor (ORM, DI container) nickname?: string; // 3. genuinely optional }

TS2564 is not saying the type is wrong. It says the compiler cannot prove the field has a value when the constructor returns. strictPropertyInitialization, switched on by strict: true, requires every declared instance property to be assigned either at the declaration or on every control-flow path through the constructor before it exits.

Two preconditions matter. The flag only has an effect while strictNullChecks is enabled; with strictNullChecks: false the check is silently skipped, which is why older codebases never saw it. And the check applies only to properties declared without ? or !, so the three options above are the whole toolkit — everything else is a variation.

Core Mechanics, Signatures & Reproducible Setup

Reproduce it in a scratch directory:

bash
mkdir ts2564 && cd ts2564 npm init -y >/dev/null && npm i -D typescript npx tsc --init --strict printf 'class User {\n email: string;\n}\nexport { User };\n' > user.ts npx tsc --noEmit

The analysis is deliberately conservative. It tracks direct assignments in the constructor, assignments inside if/else branches when every branch assigns, switch statements with a default, and try/finally blocks. It does not track:

Written codeCounts as assignedWhy
this.email = v; in the constructor bodyyesdirect assignment
constructor(public email: string)yesparameter property
if (c) this.email = a; else this.email = b;yesboth branches assign
if (c) this.email = a;noone path skips it
this.load(); where load assigns the fieldnocalls are not inlined
Object.assign(this, data);noopaque call
for (...) this.email = ...noloop may run zero times
this.email ??= "";yeslogical assignment is tracked

The reason calls are opaque is soundness: a subclass could override the method, and the compiler cannot know what an arbitrary function does to this. That single rule explains most real-world hits.

Key Comparison Table

Five ways to satisfy the compiler, and what each one costs at runtime:

FixSyntaxRuntime value if nothing assigns itBest for
Default valueemail = """"plain classes, config objects
Definite assignmentemail!: stringundefined cast to stringORM entities, DI-injected fields
Optional propertyemail?: stringundefinedtruly optional data, DTOs
Constructor parameterconstructor(public email: string)whatever the caller passesimmutable value objects
Narrow the designreadonly email: string plus constructorsame as aboveinvariants that must hold

The same problem expressed with different strictness settings:

tsconfigemail: string;Behaviour
strict: falseno errorunsafe, reads as undefined
strictNullChecks: true onlyerror TS2564check active without the rest of strict
strict: trueerror TS2564check active
strictPropertyInitialization: falseno errorper-project opt-out, keeps other strict checks

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. A method call in the constructor does not count

ts
class Config { host: string; // TS2564 port: number; // TS2564 constructor(env: Record<string, string>) { this.applyEnv(env); } private applyEnv(env: Record<string, string>) { this.host = env.HOST ?? "localhost"; this.port = Number(env.PORT ?? 3000); } }

The compiler refuses because applyEnv could be overridden and might not assign anything. The clean repair is to parse into values and assign those directly:

ts
class Config { host: string; port: number; constructor(env: Record<string, string>) { const parsed = parseEnv(env); // pure function, easy to test this.host = parsed.host; this.port = parsed.port; } }

2. ! is a promise you make to the compiler

email!: string tells TypeScript "trust me, something assigns this before anyone reads it". Nothing enforces that, so the failure moves from compile time to a TypeError: Cannot read properties of undefined at runtime, often in a completely different file. Use ! where an external framework owns the assignment — ORM hydration, dependency injection, test fixtures that set fields directly — and prefer a real default everywhere else. A quick audit is to grep for !: and confirm each hit has a documented assignment owner.

3. ORM entities and DI: declare versus !

TypeORM and Sequelize models declare columns that the library fills in:

ts
@Entity() export class Invoice { @PrimaryGeneratedColumn("uuid") id!: string; // filled by the ORM after save() @Column({ type: "numeric", precision: 12, scale: 2 }) total!: string; // numeric arrives as string in pg }

NestJS services injected through the constructor are similar:

ts
@Injectable() export class BillingService { @Inject(PAYMENT_CLIENT) private readonly client!: PaymentClient; }

declare is the variant for fields that must not be emitted at all, because a base class or decorator owns them: declare createdAt: Date; produces no createdAt = void 0 in the output, so it cannot clobber an accessor installed by a base class or a decorator.

4. useDefineForClassFields changes what "initializer" means

From target: ES2022 onward, class fields compile to real [[Define]] semantics, and TypeScript sets useDefineForClassFields: true. Three consequences show up together with TS2564:

ts
class Base { name = "base"; constructor() { console.log(this.name); } } class Child extends Base { name = "child"; // still TS2564-free, but printed value is "base" } new Child();
  1. Field initializers run after super() returns, so a base constructor that calls an overridden method sees the uninitialized field.
  2. A field with no initializer still defines the property as undefined, overwriting what a base class set.
  3. declare field: T skips the define, which is what you want for inherited state.

If a project must keep the old assignment order, set "useDefineForClassFields": false explicitly, but treat that as a temporary migration switch, not a fix.

5. Parameter properties, inheritance and constructor order

ts
abstract class Shape { constructor(public readonly name: string) {} } class Circle extends Shape { radius: number; constructor(radius: number) { super("circle"); this.radius = radius; // required, and runs after super() } }

Omitting this.radius = radius gives TS2564 even though the parameter looks like it should be enough. Only public/private/protected/readonly on a constructor parameter creates a field; a plain parameter does not. Parameter properties also cannot be used with erasableSyntaxOnly (TS 5.8+), so a project adding that flag must convert them into explicit fields — the errors arrive one field at a time.

6. DTOs, JSON parsing and optional properties

Data that arrives from fetch is not a User. Typing it as one is a lie the compiler accepts until a field is missing.

ts
type UserDto = { email?: string }; class User { email: string; // TS2564 if you keep this static from(dto: UserDto): User { const u = new User(); u.email = dto.email ?? ""; // explicit, testable return u; } }

With exactOptionalPropertyTypes: true, email?: string stops accepting undefined as a value, so { email: undefined } no longer matches the type. That is usually the behaviour you want and it keeps the optional-field escape hatch from spreading undefined through the codebase. Validating the payload (class-validator, zod) before constructing the class is cheaper than defending every read afterwards. When the payload is large, run it through the JSON formatter to see the real shape, and compare two responses with the text diff tool when a field appears only sometimes.

Common Compilation/Runtime Mistakes & Version Gotchas

Turning strict off to silence TS2564. It also disables strictNullChecks, noImplicitAny and strictFunctionTypes. The error disappears and does not come back until someone re-enables the flag, at which point the debt is larger.

Adding ! everywhere on the first pass. This is the fastest way to convert 40 compile errors into one production incident. Start with defaults, keep ! for framework-owned fields, and add a comment naming the owner.

Expecting strictPropertyInitialization: true to work alone. Before TypeScript 4.0 the flag was ignored without strictNullChecks; modern versions still do nothing useful in that combination. Set strict: true and opt out of individual checks if you must.

Assuming the compiler is running. ts-node --transpile-only, swc, esbuild, Vite and Babel all strip types without checking. A green dev server proves nothing, so put tsc --noEmit in CI.

Mutating this through Object.assign. Object.assign(this, row) reads well and assigns nothing the compiler tracks. The same problem appears with Reflect.set, lodash.merge and spread-based mixins.

Version notes. TypeScript 4.0 exempted abstract properties and declare fields. Class field emit changed with target: ES2022 in TypeScript 4.6 (useDefineForClassFields default). TS 5.8 added erasableSyntaxOnly, which rejects parameter properties and enums in files a type-stripping runtime must execute, so those fields become explicit. Reference material: strictPropertyInitialization and TypeScript classes.

Official references

primary documentation

The TypeScript documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.