日本語

Fixing TS2564 “has no initializer” Error in TypeScript Classes

​​TypeScript​Troubleshooting

error TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor. appears when a class property has no initial value and TypeScript cannot confirm that the constructor always assigns it. Adding an initial value to the property or assigning it in the constructor makes the error go away. If the value can legitimately be missing, include undefined in the type.

This article covers how to read and fix this error when you have strict enabled in tsconfig.json, you declare a property such as name: string; in a class, and either tsc fails the type check or the editor, such as VS Code, shows a red squiggle under the property name. I reproduced the error in a test environment, copied the message as it appeared, and confirmed that the error disappeared after each fix.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, npm 10.9.9, and TypeScript 7.0.2. I did not check the screen of an editor such as VS Code itself. Instead, I ran the TypeScript 7 language server (tsc --lsp --stdio) directly and checked the diagnostics it returned. I did not try versions of TypeScript before 7, and I did not try classes in frameworks that use decorators (such as Angular) or in ORMs.

The code that causes the error and its message

I ran npm init -y in an empty folder, added "type": "module" to package.json, and installed TypeScript 7.0.2. The tsconfig.json created by npx tsc --init contains "strict": true, and I used it without changes.

Below is src/user.ts, which defines a class User that holds a name and returns a greeting. name has only a type annotation and no value.

ts
class User {
  name: string;

  greet() {
    return `こんにちは、${this.name}さん`;
  }
}

const user = new User();
console.log(user.greet());

Running npx tsc --noEmit printed the following single line, and the exit code was 1.

console
$ npx tsc --noEmit
src/user.ts(2,3): error TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor.

Adding --pretty shows where the squiggle goes (colors omitted):

text
src/user.ts:2:3 - error TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor.

2   name: string;
    ~~~~


Found 1 error in src/user.ts:2

In plain terms, the message says that property name has no initializer and is not definitely assigned in the constructor. The squiggle appears on the name in the line where the property is declared (line 2, name), not in greet, where the property is used.

I also had the TypeScript 7 language server (tsc --lsp --stdio) open the same file. It returned one diagnostic with the same text as tsc. The output below is from a check script I wrote. It shows the returned diagnostics and hover, with lines and columns counted from 1 (the server name line is omitted):

text
diagnostics (1):
  2:3-2:7 severity=1 source=ts code=2564 Property 'name' has no initializer and is not definitely assigned in the constructor.
hover 2:3: (property) User.name: string

Why the error happens

This check is controlled by the tsconfig option strictPropertyInitialization. According to the TypeScript 2.7 release notes, this option is enabled together with strict. Even if strictPropertyInitialization is not written in tsconfig.json, the error appears when strict: true is set.

The property is declared as string, but right after new User(), name holds nothing. If you emit JavaScript despite the error (tsc writes output by default even when there are errors), dist/user.js looks like this:

js
class User {
    name;
    greet() {
        return `こんにちは、${this.name}さん`;
    }
}
const user = new User();
console.log(user.greet());
export {};

Here is the result of running this with Node.js:

console
$ node dist/user.js
こんにちは、undefinedさん

name, which should be a string, is actually undefined. TS2564 warns you about this mismatch between the type and the actual value before you run the code.

If there is a fixed value, write an initializer

If there is a value that is always the same, write it in the declaration:

ts
class User {
  name: string = "ゲスト";
  // greet and the code below it are the same
}

npx tsc --noEmit printed nothing and exited with code 0, and the language server returned 0 diagnostics. When the code is emitted and run, it prints こんにちは、ゲストさん.

If the value is passed when creating the instance, assign it in the constructor

If the value is received when the instance is created, as in new User("猫の手"), assign it in the constructor:

ts
class User {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet() {
    return `こんにちは、${this.name}さん`;
  }
}

const user = new User("猫の手");
console.log(user.greet());

With this, npx tsc --noEmit exited with code 0 and the language server returned 0 diagnostics. Running the code printed こんにちは、猫の手さん.

The same thing can be written by adding public to a constructor parameter (parameter properties). The parameter becomes a property with the same name, so you do not need to write the declaration and the assignment separately:

ts
class User {
  constructor(public name: string) {}
  // greet is the same
}

const user = new User("猫の手");
console.log(user.greet());
console.log(user.name);

This also passed the type check. user.greet() returned こんにちは、猫の手さん, and user.name was 猫の手.

Assigning only in some branches does not clear the error

Assigning in the constructor is not enough if the assignment is inside an if only. In the code below, the same TS2564 appeared on line 2:

ts
class User {
  name: string;

  constructor(name?: string) {
    if (name) {
      this.name = name;
    }
  }
}
console
src/user-if.ts(2,3): error TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor.

If you call new User() without passing name, this.name stays empty. According to the TypeScript 2.7 release notes, this check verifies that each property is initialized either in the constructor body or by a property initializer. In my test, the error did not go away when the assignment was only inside an if. Decide the value used when nothing is passed, and assign it unconditionally:

ts
constructor(name?: string) {
  this.name = name ?? "ゲスト";
}

With this, the type check passed. new User().name was ゲスト, and new User("猫の手").name was 猫の手.

If the value can be missing, include undefined in the type

If the name is set later, or may never be set, express the missing state in the type. Adding ? after the property name or changing the type to string | undefined stopped TS2564 from appearing. The explanation of strictPropertyInitialization also states that a property whose type includes undefined does not need to be assigned.

ts
class User {
  name?: string;

  greet() {
    return `こんにちは、${this.name.toUpperCase()}さん`;
  }
}

However, this produces a different error. name may be undefined, but the code calls a method on it directly:

console
src/user-optional.ts(5,21): error TS2532: Object is possibly 'undefined'.

At the point of use, decide what to do when the value is missing:

ts
class User {
  name?: string;

  greet() {
    return `こんにちは、${this.name ?? "ゲスト"}さん`;
  }
}

const user = new User();
console.log(user.greet());
user.name = "猫の手";
console.log(user.greet());

The type check passed with exit code 0. Running the code printed the following. When the type was written as name: string | undefined;, the type check also passed, and new User().greet() returned こんにちは、ゲストさん.

console
こんにちは、ゲストさん
こんにちは、猫の手さん

If you add ? only to make the error go away, you get errors at the places that use the value without checking it, as shown above. Think about whether a missing state can really happen before choosing this option.

If a method called from the constructor does the assignment, add !

Sometimes initialization is moved into a method that the constructor calls:

ts
class User {
  name: string;

  constructor() {
    this.reset();
  }

  reset() {
    this.name = "ゲスト";
  }
}

reset always assigns name, but this code still produced TS2564 on line 2. According to the --strictPropertyInitialization section of the classes chapter of the handbook, the assignment must be made directly in the constructor, and TypeScript does not check inside methods that the constructor calls. The reason given is that a derived class can override that method and stop assigning the property.

When you know the property is always assigned in a way TypeScript cannot see, add ! after the property name. The TypeScript documentation calls this the "definite assignment assertion."

ts
class User {
  name!: string;
  // constructor and reset are the same
}

console.log(new User().name);

With this, npx tsc --noEmit exited with code 0, and running the code printed ゲスト.

Warning

! tells the compiler not to check whether the property is assigned. Adding ! to a property that is never assigned still passes the type check. I wrote name!: string; without any assignment and called this.name.toUpperCase() inside greet. tsc reported nothing, but running the code stopped with TypeError: Cannot read properties of undefined (reading 'toUpperCase').

Setting strictPropertyInitialization to false turns off the check

Setting "strictPropertyInitialization": false in compilerOptions in tsconfig.json disables this check. I ran npx tsc --noEmit --strictPropertyInitialization false on the original src/user.ts. TS2564 did not appear, and the exit code was 0.

However, this does not fix the mismatch that caused the error. It only hides it. Even with this setting, the emitted code still printed こんにちは、undefinedさん when run, so name was still undefined. With this setting, you lose the ability to catch missing initialization in every class in the project. It is safer to choose, for each property, between an initializer, an assignment in the constructor, a type that includes undefined, and !.

​Posted by 86