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

How to solve Circular Dependencies when useing classes as Types in Typescript?

我如何使用不会 运行 进入循环依赖错误的打字稿?

似乎发生了循环依赖错误,即使在代码编译为有效的 JS 时应该删除导入。这是一个错误吗?

用户-model.ts

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

export class User {
  Posts: Post[];
}

post-model.ts

import { User } from '../user-model'

export class Post {
  User: User;
}

我听说过两种可能的解决方案,但我都不满意。

一种是,创建一个与 class 匹配的新界面:

而且我在 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.

我也没有找到任何选项来禁用打字稿中的循环依赖警告。

我在Nrwl/Angular9.x

工作

提前感谢您的帮助!

只有将它们放在同一个文件中才能执行此操作

export class User {
  Posts: Post[];
}

export class Post {
  User: User;
}

或者如果你写它们类型

用户-post.types.ts

export interface User {
  Posts: Post[];
}

export interface Post {
  User: User;
}

用户-model.ts

import { Post } from '../user-post.types'

export class User {
  Posts: Post[];
}

post-model.ts

import { User } from '../user-post.types'

export class Post {
  User: User;
}

在这里使用接口是最好的选择。您可以为每个制作一个 .d.ts,然后导入它。

user.d.ts

export interface IUser {
  Posts: IPost[];
}

post.d.ts

export interface IPost {
  User: IUser;
}

然后...

import { IPost, IUser } from './post.d'

export class User implements IUser {
  Posts: IPost[];
}

另一种不使用接口的解决方案是使用type only imports

用户-model.ts

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

export class User {
  Posts: Post[];
}

用户-model.ts

import type { User } from './user-model'

export class Post {
  User: User;
}

这些导入在编译时被完全删除,仅用于类型检查 - 这意味着您不能将它们用作值(您不能使用仅类型导入 new Post()例如)。

我认为这种方法比仅出于类型检查的目的创建带有接口的单独文件的替代方法更干净、更干。