You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现TypeScript函数根据输入类型确定返回类型(TypeORM场景)

解决TypeORM泛型查询函数的类型匹配问题

问题分析

你想要实现一个泛型函数,根据传入的实体类(User/Address)返回对应类型的数组,但当前泛型写法导致{ id: In(ids) }出现类型不兼容错误——TypeScript无法确定泛型EntityType的id字段类型,因此无法匹配FindOptionsWhere的类型要求。

解决方案

通过给泛型添加明确的类型约束,确保EntityType拥有数字类型的id字段,让TypeScript能正确推断查询条件的类型:

修改后的代码

type Q = User | Address;

async function b<EntityType extends Q & { id: number }>(
  entityClass: EntityTarget<EntityType>,
  em: EntityManager,
  ids: number[]
): Promise<EntityType[]> {
  const e = await em.findBy(entityClass, { id: In(ids) });
  return e;
}

可选优化:提取通用约束接口

如果有更多实体需要复用这个约束,可以单独定义一个接口:

interface HasNumericId {
  id: number;
}

type Q = User | Address;

async function b<EntityType extends Q & HasNumericId>(
  entityClass: EntityTarget<EntityType>,
  em: EntityManager,
  ids: number[]
): Promise<EntityType[]> {
  const e = await em.findBy(entityClass, { id: In(ids) });
  return e;
}

错误原因说明

之前的泛型仅约束EntityType extends Q,但TypeScript无法从该约束中确定EntityType['id']的具体类型(即使实际业务中User和Address的id都是数字,泛型层面未明确声明)。此时In(ids)返回的FindOperator<any>无法匹配FindOptionsWhereProperty<NonNullable<EntityType["id"]>>的类型要求,因此抛出类型错误。添加& { id: number }的约束后,TypeScript明确知道id是数字类型,就能正确匹配In(ids)的查询类型。

内容的提问来源于stack exchange,提问作者sev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 12:05:21