如何将Hashids返回的NumberLike[]安全转换为number适配Prisma?
解决Hashids解码结果与Prisma id类型不兼容问题
我正在使用Hashids,它定义了如下类型:
export declare type NumberLike = bigint | number;
解码代码如下:
const id = hashids.decode(handler)
在Prisma中执行查询时出现类型不兼容:
const entry = await prisma.entry.findUnique({ where: { id: id, // Type 'NumberLike[]' is not assignable to type 'number'.ts(2322) }, })
报错信息:
Type 'NumberLike[]' is not assignable to type 'number'.ts(2322)
解决方案
Hashids的decode方法返回的是NumberLike[]类型数组,而Prisma需要单个number类型的id,按以下步骤处理:
- 提取数组中的第一个元素:单个Hashid编码解码后通常返回包含一个元素的数组,直接取索引0的元素。
- 校验并转换类型:区分bigint和number类型,将bigint安全转为number(注意数值范围限制)。
具体代码实现:
const decodedIds = hashids.decode(handler); // 先校验解码结果是否有效 if (!decodedIds.length) { throw new Error('无效的Hashid编码'); } const rawId = decodedIds[0]; // 转换为number类型 const entryId: number = typeof rawId === 'bigint' ? Number(rawId) : rawId; // 执行Prisma查询 const entry = await prisma.entry.findUnique({ where: { id: entryId, }, });
注意事项
- 如果你的业务场景是解码多个id的Hashid编码,需要根据实际逻辑遍历数组处理,而非仅取第一个元素。
- 当bigint数值超过
Number.MAX_SAFE_INTEGER(2^53-1)时,用Number()转换会丢失精度,此时建议将Prisma模型中的id字段类型改为BigInt,或者确保编码的数值在安全范围内。
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

