简体   繁体   中英

refect-metadata "design:type" circular dependency

In this repo you can clearly see that both of the classes have metadata design:type on the properties. Only one of them though shows when I try to probe for it. Can someone explain?

As described here https://github.com/rbuckton/reflect-metadata/issues/135#issuecomment-985998206 :

This is a known limitation of the metadata format that Typescript emits. Newer metadata systems use a "resolver" pattern to get around this- for instance instead of using a SomeClass reference in the metadata, it will use () => SomeClass and expect the code retrieving the metadata to execute the function to obtain the class (constructor) reference.

The underlying reason is because in the case of a circular dependency, the inner required file is executed fully at the point in the outer file where it is imported. Code declared after the import occurs has not run yet. This is true of both CommonJS and ES modules, but in ES modules the name you give to an import is bound to the equivalent name which is exported from the imported file-- that is to say it is "live"-- so after both files are fully loaded the values are correct, this is why the "resolver" pattern works.

Getting around this can be painful / impossible without rearranging your code. Some libraries like TypeORM use the resolver pattern directly to allow for circular dependencies while still using the standard Typescript metadata emitting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM