typescript - 在 Typescript 中使用类作为类型时如何解决循环依赖关系?

标签 typescript typescript-typings circular-dependency typegraphql

如何使用不会遇到循环依赖错误的 typescript ?
似乎发生了循环依赖错误,即使在代码编译为有效 JS 时应该删除导入。那是一个错误吗?
用户模型.ts

import { Post } from '../post-model'

export class User {
  Posts: Post[];
}
模型后.ts
import { User } from '../user-model'

export class Post {
  User: User;
}
我听说过两种可能的解决方案都不能让我满意。
一种是,创建一个与类匹配的新接口(interface):
Circular dependency caused by importing typescript type
我在 typegraphql 的文档中读过一些东西:
https://typegraphql.com/docs/types-and-fields.html
他们在那里说:

Why use function syntax and not a simple { type: Rate } config object? Because, by using function syntax we solve the problem of circular dependencies (e.g. Post <--> User), so it was adopted as a convention. You can use the shorthand syntax @Field(() => Rate) if you want to save some keystrokes but it might be less readable for others.


我也没有找到任何选项来禁用 typescript 中的循环依赖警告。
我在 Nrwl/Angular 9.x 工作
提前感谢您的帮助!

最佳答案

另一个不使用接口(interface)的解决方案是使用 type only imports .
用户模型.ts

import type { Post } from './post-model'

export class User {
  Posts: Post[];
}
用户模型.ts
import type { User } from './user-model'

export class Post {
  User: User;
}
这些导入在编译时被完全删除,仅用于类型检查 - 这意味着您不能将它们用作值(例如,您不能使用仅类型导入来执行 new Post())。
我认为这种方法比只为了类型检查而创建带有接口(interface)的单独文件的替代方法更干净、更干燥。

关于typescript - 在 Typescript 中使用类作为类型时如何解决循环依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61259112/

相关文章:

javascript - 从 tinymce 触发的 MatDialog 在窗口调整大小之前未初始化

javascript - 为什么 Record<string, any> 可以等于 Functions?

typescript - 当返回 Promise then 时,但得到 `Property ' then' 在类型 'Promise<number>' 上不存在`

typescript - 参数隐式具有 'any' 类型

typescript - 如何在 TypeScript 中引用属于联合类型的类型?

angular - 当那个面板的表单组无效时,如何打开mat-expansion-panel?

typescript - 寻找由模板文字类型的任何可能组合组成的 TypeScript 类型

python - Python 中 "import lib.foo"和 "import lib.foo as f"的区别

c++ - Typedef 循环依赖

javascript - 为什么我的函数会导致 TypeError <function> is not a function?