typescriptvisual-studio-codedependency-injectiontypescript-decoratortsyringe

Error using tsyringe decorators in typescript


I'm trying to use tsyringe typescript library but couldn't even add any decorators as VsCode complains about them.

I'm using typescript 5.

Here's the tsconfig.json - it has the required experimentalDecorators and emitDecoratorMetadata documented by tsyringe docs.

{
   "compilerOptions": {
      "baseUrl": "src/",
      "declaration": true,
      "declarationDir": "build/",
      "emitDeclarationOnly": true,
      "esModuleInterop": true,
      "target": "ESNext",
      "useDefineForClassFields": true,
      "module": "ESNext",
      "lib": [
         "ESNext",
         "DOM",
         "DOM.Iterable",
         "ES2021.String"
      ],
      "moduleResolution": "Node",
      "strict": true,
      "resolveJsonModule": true,
      "isolatedModules": true,
      "noUnusedLocals": false,
      "noUnusedParameters": false,
      "noImplicitReturns": true,
      "skipLibCheck": true,
      "typeRoots": [
         "node_modules/@types"
      ],
      "experimentalDecorators": true,
      "emitDecoratorMetadata": true
   },
   "include": [
      "./src/*", "@types"
   ],
   "exclude": [
      "./src/tests/**"
   ]
}

Errors:

Unable to resolve signature of class decorator when called as an expression

@injectable()
export class WorkerRuntime implements Runtime { ... }

Decorators are not valid here

constructor(@inject("pageMonitor") private pageAwaiter: Awaiter, ...)

UPDATE

Here's the directory structure

C:.
│   package.json
│   tsconfig.json
│
└───src
    │   index.ts
    │   runtime.ts
    │
    ├───content
    │   │   content.runtime.ts
    │   │   index.ts
    │
    └───worker
        │   index.ts
        │   worker.runtime.ts

UPDATE 2

If I use the @injectable in a file directly under src, VsCode does not complain - like runtime.ts file. But if I use it in a file within a folder under src like src/worker/worker.runtime.ts VsCode complains. However, I cannot change the tsconfig.json to include: ["./src/**"] (double star) - it does not allow it:

File specification cannot end in a recursive directory wildcard ('**'): './src/**'

What am I missing?


Solution

  • Hard to tell without knowing your files and folders structure, but these errors means that experimentalDecorators is not taken into account, and I highly suspect it's because your TypeScript file location either does not match the glob patterns you have configured in the include property, or matches the exclude pattern.