Skip to content

fix: importsNotUsedAsValues: remove breaks DI #778

Open
@mt3o

Description

@mt3o

Description

Hi!

I think you should expand your documentation by adding a point about enabling "importsNotUsedAsValues": "preserve" in tsconfig.json.

By default typescript removes unused imports, so if class is not imported & instantiated by hand, the call gets removed, and as effect, typedi is unaware of class existence. Enabling the mentioned rule changes the behavior - and explicit import saves the day.

People coming from other languages (java, dot net) or even python might be at difficulty with this behavior. Usually the DI container scans the codebase and detects all classes annotated with @Service or other annotation. Typedi on the other hand - doesn't. If the code is not explicitly executed, class can't be injected.

This pattern is useful when we split interface/abstract class from the implementation/concrete class, and put them in separate files. But not with typedi. Interface gets imported, implementation is not, typedi can't inject. Your tests involving inheritance work because everything stays in the same file. If you put classes into separate files - it will not work.

I made an abstracted sample: (https://github.com/mt3o/typedi-caveat)

Expected behavior

Ideal solution would be to autoscan classes.
Good enough would be to instruct the developer to change tsconfig.json and explicitly import all classes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: needs triageIssues which needs to be reproduced to be verified report.type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions