When defining entities with TypeORM and TypeScript, you may encounter an annoying issue as follows:
Property 'id' has no initializer and is not definitely assigned in the constructor
The warnings are present not only in the id field but also in all other fields in my classes entity:
The culprit here is related to strict checking of property initialization in classes. To solve the problem, we have to disable this feature. In your tsconfig.json file, find strictPropertyInitialization and set it to false:
You may have to reload or restart VS Code (or whatever code editor you are using) to make the irritating warnings go away.
Here’s my entire tsconfig.json (with comments removed) for your reference:
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false,
"emitDecoratorMetadata": true
}
}
Further reading:
- TypeORM: Adding created_at and updated_at columns
- Node + Mongoose + TypeScript: Defining Schemas and Models
- Express + TypeScript: Extending Request and Response objects
- Node + TypeScript: Export Default Something based on Conditions
- Using Rest Parameters in TypeScript Functions
- Best Node.js frameworks to build backend APIs
You can also check out our Node.js category page for the latest tutorials and examples.