Reputation: 79
I'm running into a circular dependency detected warning in an Angular app using individually exported functions from two utility files. I'll show a simplified example of the two files below.
The first file:
// type-helper.ts
import {getPropertyIfExists} from "./helper";
export function isType(item: any, type: string, property?: string) {
const target = getPropertyIfExists(item, property);
if (typeof type !== "string") return false;
else return typeof target === type;
}
export function isArray(item: any[] | any): item is any[] {
return item && Array.isArray(item);
}
export function isObject(item: object | any): item is object {
return item && typeof item === 'object';
}
The second file:
// helper.ts
import {isArray, isObject} from "./type-helper";
export function getPropertyIfExists(item: any, property?: string): any {
if (property) return item[property];
else return item;
}
export function removeUndefinedProperties<T>(obj: T): T {
const keys = Object.keys(obj);
for (const key of keys) {
if (isArray(obj[key])) obj[key] = removeEmptyValuesFromArray(obj[key]);
else if (isObject(obj[key])) obj[key] = removeUndefinedProperties(obj[key]);
else if (item === undefined || item === null) delete obj[key];
}
return obj;
}
Both of these files provide small utilities that I like reusing in my application without necessarily being linked to a single service. As far as I can tell, there are no other links between these files.
So, my questions:
Thanks!
Upvotes: 1
Views: 1560
Reputation: 2397
index.ts from utilities folder is a barrel module (A barrel is a way to rollup exports from several modules into a single convenient module. The barrel itself is a module file that re-exports selected exports of other modules.)
You cannot import the barrel module itself. Because the circular dependence will appear. (an infinite loop of imports will be made)
index.ts
type-helper.ts
helper.ts
helper.ts -> index.ts -> type-helper.ts
-> helper.ts -> index.ts -> type-helper.ts
-> helper.ts
To prevent this, you need to import the exact patch
// helper.ts
// import {isArray, isObject} from "./helper";
import {isArray, isObject} from "./helper/type-helper";
export function getPropertyIfExists(item: any, property?: string): any {
if (property) return item[property];
else return item;
}
export function removeUndefinedProperties<T>(obj: T): T {
const keys = Object.keys(obj);
for (const key of keys) {
if (isArray(obj[key])) obj[key] = removeEmptyValuesFromArray(obj[key]);
else if (isObject(obj[key])) obj[key] = removeUndefinedProperties(obj[key]);
else if (item === undefined || item === null) delete obj[key];
}
return obj;
}
You probably have helper.ts instead of index.ts
it's the same thing
helper.ts -> type-helper.ts -> helper.ts -> type-helper.ts ...
move the getPropertyIfExists() function into type-helper.ts
Upvotes: 1