Search code examples
typescripttypeorm

Using decorators is failing in typeorm


I am new to type ORM, and I'm new to using decorators as well in TypeScript, I am getting an error, I believe it's regarding the --strictPropertyInitialization flag set by the typescript rules.

I have no idea how to overcome this problem, what am I doing wrong?

import { Entity } from 'typeorm'

@Entity({ name: 'test' })
export class Photo {
  id: number
}
Property 'id' has no initializer and is not definitely assigned in the constructor.ts(2564)

enter image description here

My tsconfig.json:

{
  "compilerOptions": {
    "target": "es2016",
    "module": "ESNext",
    "lib": ["ES6"],
    "moduleResolution": "Node",
    "rootDir": "./src",
    "baseUrl": "./src",
    "paths": {
      "@/*": ["./*"],
      "@tools/*": ["./tools/*"],
      "@types/*": ["./types/*"],
      "@server/*": ["./server/*"],
      "@routes/*": ["./routes/*"],
      "@models/*": ["./models/*"],
      "@schemas/*": ["./schemas/*"],
      "@constants/*": ["./constants/*"],
      "@middlewares/*": ["./middlewares/*"]
    },
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "outDir": "./dist",
    "removeComments": true,
    "declarationDir": "./@types",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "plugins": [{ "transform": "typescript-transform-paths" }]
  },
  "ts-node": {
    "require": ["tsconfig-paths/register"]
  },
  "exclude": ["./@types", "node_modules"],
  "include": ["./src/**/*"]
}

What could be the reason to this error?

I read about it here, but I'm not sure how to solve it


Solution

  • Add "strictPropertyInitialization": false to the "compilerOptions" object of your tsconfig.json:

    {
      "compilerOptions": {
        "strict":true, 
        "strictPropertyInitialization": false, 
        // etc.
      }
    }
    

    This is equivalent to specifying the command line flag

    tsc -p ./tsconfig.json --strictPropertyInitialization false
    

    Note that when we enable strict, "strict": true we enable the whole family of strict checks, that is all compiler options beginning with the term strict. This is usually desirable but in case we need to disable one, we can use the above approach.