Java / Typescript中循环依赖问题的精美修复 [英] Beautiful fix for circular dependecies problem in Javascript / Typescript

查看:89
本文介绍了Java / Typescript中循环依赖问题的精美修复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在构建我正在研究的项目时,我偶然发现了循环依赖问题:一个小型的ORM,用于学习。



最小化项目可以重现该问题可以在此处找到。这是一个更简单的概述:



文章

  import'./ManyToMany'中的{ManyToMany}; 
从 ./Tag导入{标签};

出口类别文章{
@ManyToMany(Tag)
标签:Tag [] = [];
}

ManyToMany

  //无导入
导出函数ManyToMany(entity){

}

标签



< pre class = lang-js prettyprint-override> import {ManyToMany} from'./ManyToMany';
从 ./Article中导入{Article};

出口类别标签{
@ManyToMany(Article)
articles:Article [] = [];
}

重要的是,代码不要过多更改或根本不更改,因为这影响DX。我不希望该库的用户创建其他黑客文件来解决此问题。



我找到了一个讨论列表,但没有一个很优雅: p>



我能找到的最佳解决方案是使用内部模块模式。此解决方案和所有其他解决方案只是解决该问题的方法和变通办法,实际上并未解决。



是否有一种更好,更优雅的解决方案,而无需创建其他文件或移动

解决方案

根据Bergi的评论,可行的解决方案是使引用变得惰性,即传递一个返回值的函数。实体,并且不会立即对其进行评估(在属性修饰期间),但稍后会在加载所有模块,初始化类并创建第一个实例时进行评估。



我尝试实施相同的 https: //stackblitz.com/edit/typescript-f5rm9u 在这里。请检查实施情况。



ManyToMany

 导出函数ManyToMany(entity =()=>实体){
返回函数(目标,名称){
console.log(entity.name);
};
}

答案信用:@Bergi


I just stumbled upon the circular dependency problem when building a project I am working on: a small ORM, for learning purposes.

Minimal project to reproduce the problem can be found here. Here is an even simpler overview:

Article:

import { ManyToMany } from './ManyToMany';
import { Tag } from './Tag';

export class Article {
    @ManyToMany(Tag)
    tags: Tag[] = [];
}

ManyToMany:

//no imports
export function ManyToMany(entity) {
    …
}

Tag:

import { ManyToMany } from './ManyToMany';
import { Article } from './Article';

export class Tag {
    @ManyToMany(Article)
    articles: Article[] = [];
}

It is important that the code is not changed too much or at all because this affects the DX. I don't want the users of this library to create additional hacky files to fix this problem.

I found a list of discussions but none of them are elegant:

The best solution that I could find is using the internal module pattern. This and all other solutions are just hacks and workarounds to this problem and none actually fixes it.

Is there a better, more elegant solution to this without creating additional files or move code around?

解决方案

As per Bergi's comment, the solution that would work is to make the reference lazy i.e. pass a function returning the entity and do not evaluate it immediately (during the property decoration) but later when all the modules are loaded, the classes initialized, and the first instance is being created.

I have tried to implement the same https://stackblitz.com/edit/typescript-f5rm9u here. Please check the implementation.

ManyToMany

export function ManyToMany(entity=() => entity) {
    return function(target, name)  {
        console.log(entity.name);
    };
}

Answer credit: @Bergi

这篇关于Java / Typescript中循环依赖问题的精美修复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆