如何使用不会遇到循环依赖错误的 typescript ?
似乎发生了循环依赖错误,即使在代码编译为有效 JS 时应该删除导入。那是一个错误吗?
用户模型.ts
import { Post } from '../post-model'
export class User {
Posts: Post[];
}
模型后.tsimport { 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[];
}
用户模型.tsimport type { User } from './user-model'
export class Post {
User: User;
}
这些导入在编译时被完全删除,仅用于类型检查 - 这意味着您不能将它们用作值(例如,您不能使用仅类型导入来执行 new Post()
)。我认为这种方法比只为了类型检查而创建带有接口(interface)的单独文件的替代方法更干净、更干燥。
关于typescript - 在 Typescript 中使用类作为类型时如何解决循环依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61259112/