MikroORM7.2 中文文档
入门指南/第 5 章:类型安全
已译 96/96

第 5 章:类型安全

现在我们已经有了一个带实体、关联关系以及由 QueryBuilder 驱动的列表查询的博客 API,接下来看看 MikroORM 的类型系统如何在编译期保证一切安全。

Loaded 类型与 populate 提示

如果你检查 em.find 与 em.findOne 的返回类型,可能会注意到它们并不直接返回实体——而是返回一个 Loaded 类型:

// res1 的类型是 `Loaded<Article, never>[]`
const res1 = await em.find(ArticleSchema, {});

// res2 的类型是 `Loaded<Article, 'author'>[]`
const res2 = await em.find(ArticleSchema, {}, { populate: ['author'] });

Loaded 类型会记录哪些关联已被填充,并为它们添加一个特殊的 $ 符号,用于类型安全的同步访问。它与 Reference 包装器(下一节介绍)配合得非常好:

// article 的类型是 `Loaded<Article, 'author'>`
const article = await em.findOneOrFail(ArticleSchema, 1, { populate: ['author'] });

// 对已加载的 author 进行类型安全的同步访问:
console.log(article.author.$.fullName);

如果你省略 populate 提示,article 的类型就会是 Loaded<Article, never>,此时 article.author.$ 符号不可用——这样的调用最终会导致编译错误。

// 没有 populate 时,类型是 `Loaded<Article, never>`
const article2 = await em.findOneOrFail(ArticleSchema, 2);

// TS2339: Property '$' does not exist on type '...'
console.log(article2.author.$.fullName);

对于 OneToMany/ManyToMany 关联上的 Collection 包装器也是如此:

// user 的类型是 `Loaded<User, 'articles'>`
const user = await em.findOneOrFail(User, 1, { populate: ['articles'] });

// 对已加载的集合元素进行类型安全的同步访问:
for (const article of user.articles.$) {
  console.log(article.title);
}

如果你不喜欢 $ 这种带魔法名字的符号,可以改用 get() 方法,它是前者的别名。

你也可以在自己的函数中使用 Loaded 类型,以要求某些关联必须已被填充:

function publishArticle(article: Loaded<Article, 'author'>) {
  // 我们可以安全地访问 author,无需任何异步加载
  console.log(`Publishing "${article.title}" by ${article.author.$.fullName}`);
}
// 可以通过——author 已填充
const a1 = await em.findOneOrFail(ArticleSchema, 1, { populate: ['author'] });
publishArticle(a1);

// 编译错误——author 未填充
const a2 = await em.findOneOrFail(ArticleSchema, 1);
publishArticle(a2);

请记住,这些都只是类型层面的信息,你完全可以通过类型断言绕过它。

Reference 包装器

当你定义 manyToOne 或 oneToOne 关联时,TypeScript 会认为关联实体总是已加载的:

const article = await em.findOne(ArticleSchema, 1);
console.log(article.author.fullName); // undefined,User 还没有被加载!

你可以通过使用 Reference 包装器来克服这个问题。它会包装实体,并定义一个 load(): Promise<T> 方法——如果关联尚不可用,它会惰性加载它。使用 defineEntity 时,你通过 .ref() 启用它:

article.entity.ts
import { defineEntity, type InferEntity, p } from '@mikro-orm/core';
import { BaseSchema } from '../common/base.entity.js';
import { UserSchema } from '../user/user.entity.js';

export const ArticleSchema = defineEntity({
  name: 'Article',
  extends: BaseSchema,
  properties: {
    // ...
    // 用 .ref() 把关联包装进 Reference
    author: () => p.manyToOne(UserSchema).ref(),
  },
});

export type IArticle = InferEntity<typeof ArticleSchema>;

现在该属性的类型变为 Ref<User>,这可以防止意外访问未加载的属性:

const article1 = await em.findOne(ArticleSchema, 1);
article1.author;       // Ref<User>(Reference 类的实例)
article1.author.fullName;  // 类型错误!Ref<User> 上没有 `fullName` 属性
article1.author.id;    // 可以,主键在 Ref 上总是可用的

const article2 = await em.findOne(ArticleSchema, 1, { populate: ['author'] });
article2.author;          // LoadedReference<User>
article2.author.$.fullName; // populate 之后可类型安全地同步访问

使用 Reference.load()

拿到引用之后,你可以通过异步的 load() 方法加载完整实体:

const article = await em.findOne(ArticleSchema, 1);
const author = await article.author.load();
author.fullName; // 可以,author 现在已加载

await article.author.load(); // 不会产生额外查询,已经加载过了

与总是刷新实体的 wrap(e).init() 不同,Reference.load() 只会在实体尚未加载到标识映射中时才查询数据库。

LazyRef<T>——纯类型层面的替代方案

如果 Reference 的 .$/.get() 间接层不符合你的风格(例如你正从非 Ref 的代码库迁移过来),可以改用 LazyRef<T>。运行时它仍然是普通实体——article.author instanceof User 为 true,没有包装器——但在 Loaded<> 收窄类型之前,TypeScript 依然会限制对非主键成员的访问:

article.entity.ts
author: () => p.manyToOne(UserSchema).lazyRef(),
const article1 = await em.findOne(ArticleSchema, 1);
article1.author.id;       // 可以——主键总是可访问
article1.author.fullName; // 类型错误——未加载

const article2 = await em.findOne(ArticleSchema, 1, { populate: ['author'] });
article2.author.fullName; // 可以——Loaded<> 会去掉 LazyRef 标记,无需 `.$`

关于它与 Ref<T> 的完整对比以及 unref() 这个逃生舱,请参见类型安全的关联 → LazyRef<T>。

ScalarReference 包装器

与 Reference 包装器类似,你也可以用 Ref 把标量包装成 ScalarReference 对象。这对惰性标量属性很方便。

对于非对象类型,Ref 类型会自动解析为 ScalarReference,所以下面这段是正确的:

// 在我们的 Article 实体中,`text` 属性是惰性的。
// 如果用 .ref() 包装它,它就会变成 ScalarReference:
text: p.text().lazy().ref(),
const article = await em.findOne(ArticleSchema, 1);
const text = await article.text.load(); // 加载惰性的 text 属性
使用装饰器

如果你把装饰器与 reflect-metadata 一起使用,就需要显式设置 ref 选项:

@ManyToOne(() => User, { ref: true })
author!: Ref<User>;

使用 defineEntity 时,.ref() 方法会自动处理这一点。

用 fields 做严格的部分加载

Loaded 类型同样会遵循部分加载提示(fields 选项)。使用它时,返回的类型只允许访问被选中的属性。主键总是会被自动选中并可用。

// article 的类型是 `Selected<Article, 'author', 'title' | 'author.email'>`
const article = await em.findOneOrFail(ArticleSchema, 1, {
  fields: ['title', 'author.email'],
  populate: ['author'],
});

const id = article.id;           // 可以,主键会被自动选中
const title = article.title;     // 可以,title 被选中
const slug = article.slug;       // 失败,未被选中
const authorId = article.author.id;    // 可以,主键会被自动选中
const email = article.author.email;    // 可以,已选中
const name = article.author.fullName;  // 失败,未被选中

QueryBuilder 的类型安全

在第 4 章中,我们用 QueryBuilder 构建了文章列表查询。MikroORM 的 QueryBuilder 拥有完全类型安全的 API,它会在类型层面追踪别名、被 join 的实体以及被选中的字段。

上下文感知的 join

每次 join/leftJoin 调用都会往 Context 类型参数中追加内容,用于记录有哪些别名可用以及它们分别指向什么实体类型:

const qb = em.createQueryBuilder(ArticleSchema, 'a')
  .leftJoin('a.author', 'u');  // Context 现在知道别名 'u' 映射到 User

在 join 之后,TypeScript 知道 'u' 是一个指向 User 实体的有效别名,并会校验它后续的任何用法。

严格的 select

select 方法会校验字段路径是否使用了已知别名与合法的属性名:

const qb = em.createQueryBuilder(ArticleSchema, 'a')
  .leftJoin('a.author', 'u')
  .select(['a.title', 'u.fullName']);  // 可以:'a' 是 Article,'u' 是 User

// 编译错误:'x' 不是已知别名
em.createQueryBuilder(ArticleSchema, 'a')
  .select(['a.title', 'x.invalid']);

你也可以用 addSelect 添加更多字段,包括原生 SQL 片段:

em.createQueryBuilder(ArticleSchema, 'a')
  .select(['a.slug', 'a.title'])
  .leftJoin('a.author', 'u')
  .addSelect(sql.ref('u.full_name').as('authorName'));

严格的 where

where 方法会针对已知别名及其实体类型校验带别名的对象条件:

const qb = em.createQueryBuilder(ArticleSchema, 'a')
  .leftJoin('a.author', 'u');

// 可以:'u' 映射到 User,而它有 `fullName` 属性
qb.where({ 'u.fullName': 'Jon' });

// 可以:'a' 映射到 Article,而它有 `title` 属性
qb.where({ 'a.title': 'Hello World' });

// 编译错误:'x' 不是已知别名
qb.where({ 'x.foo': 1 });

这对嵌套条件同样有效:

qb.where({
  $or: [
    { 'a.title': { $like: '%orm%' } },
    { 'u.fullName': 'Jon' },
  ],
});

joinAndSelect 的结果类型

当你使用 joinAndSelect 或 leftJoinAndSelect 时,Hint 类型参数会被自动更新,因此 getResultList() 会返回类型正确的 Loaded 实体:

const articles = await em.createQueryBuilder(ArticleSchema, 'a')
  .leftJoinAndSelect('a.author', 'u')
  .getResultList();
// articles 的类型是 `Loaded<Article, 'author'>[]`

// 对已加载的 author 进行类型安全的访问:
articles[0].author.$.fullName; // 可以

这等价于使用带 populate: ['author'] 的 em.find,但拥有 QueryBuilder API 的灵活性。

select 的结果类型

当你用 select 挑选特定字段时,Fields 类型参数会记录哪些字段被选中了:

const articles = await em.createQueryBuilder(ArticleSchema, 'a')
  .select(['a.title', 'a.description'])
  .getResultList();
// articles 的类型是 `Loaded<Article, never, 'title' | 'description'>[]`

articles[0].title;       // 可以,已选中
articles[0].description; // 可以,已选中
articles[0].slug;        // 失败,未被选中
articles[0].id;          // 可以,主键总是可用

await 一个 QueryBuilder

你可以直接 await 一个 QueryBuilder 实例。返回类型取决于你正在构建哪种查询:

// SelectQueryBuilder → await 得到实体数组
const articles = await em.qb(ArticleSchema)
  .select('*')
  .where({ title: { $like: '%orm%' } })
  .limit(5);
// articles 的类型是 Article[]

// CountQueryBuilder → await 得到数字
const count = await em.qb(ArticleSchema)
  .count()
  .where({ title: { $like: '%orm%' } });
// count 的类型是 number

// InsertQueryBuilder → await 得到 QueryResult
const res1 = await em.qb(ArticleSchema).insert({
  title: 'New Article',
  text: 'Content here',
  author: 1,
});
// res1 的类型是 QueryResult<Article>
console.log(res1.insertId);

// UpdateQueryBuilder → await 得到 QueryResult
const res2 = await em.qb(ArticleSchema)
  .update({ title: 'Updated' })
  .where({ id: 1 });
// res2 的类型是 QueryResult<Article>
console.log(res2.affectedRows);

// DeleteQueryBuilder → await 得到 QueryResult
const res3 = await em.qb(ArticleSchema)
  .delete()
  .where({ id: 1 });
// res3 的类型是 QueryResult<Article>

em.qb() 是 em.createQueryBuilder() 的快捷方式。

给 Reference 属性赋值

当你把属性定义为 Reference 包装器时,你需要给它赋一个 Reference 实例,而不是实体本身。你可以通过 ref(entity) 把任意实体转换成 Reference,或者使用 em.getReference() 的 wrapped 选项:

ref(e) 是 wrap(e).toReference() 的快捷方式,而后者等同于 Reference.create(e)。

import { ref } from '@mikro-orm/core';

const article = await em.findOne(ArticleSchema, 1);
const repo = em.getRepository(User);

article.author = repo.getReference(2, { wrapped: true });

// 等价于:
article.author = ref(repo.getReference(2));
await em.flush();

你也可以使用 rel() 辅助函数,在不访问 EntityManager 的情况下创建实体引用:

import { rel } from '@mikro-orm/core';

const article = em.create(ArticleSchema, {
  title: 'New Article',
  text: 'Content here',
  author: rel(User, 1),
});