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

使用Lodash _.mergeWith合并对象忽略Null时遇TypeScript ESLint错误求正解

解决Lodash _.mergeWith忽略null值时的TypeScript ESLint错误

问题分析

你遇到的@typescript-eslint/no-unsafe-return错误,本质是TypeScript无法自动推断_.mergeWith回调函数中参数a和b的具体类型,导致返回值被推断为any,触发ESLint的类型安全检查规则。用:any临时规避虽然能消除报错,但会关闭该位置的类型校验,存在潜在风险。

正确解决方案

1. 为回调参数指定具体类型

如果你的child和parent属于同一自定义类型(比如User),可以直接为回调的a、b参数明确类型:

// 先定义你的对象类型
type User = {
  name?: string;
  age?: number;
  avatar?: string | null;
};

const child: User = { name: "Alice", age: 25 };
const parent: User = { name: null, age: 30, avatar: "url" };

const merged = _.mergeWith(child, parent, (a: User[keyof User], b: User[keyof User]) => {
  return _.isNull(b) ? a : b;
});

2. 用泛型函数封装(更通用)

如果需要复用这个合并逻辑,建议封装成泛型函数,让TypeScript自动推导类型:

function mergeObjectsWithoutNull<T extends Record<string, unknown>>(child: T, parent: T): T {
  return _.mergeWith(child, parent, (a, b) => {
    return _.isNull(b) ? a : b;
  });
}

// 使用时直接传入同类型对象,类型自动推导
const merged = mergeObjectsWithoutNull(child, parent);

3. 利用Lodash的类型定义(简化版)

如果不想手动定义类型,也可以直接复用Lodash内置的MergeCustomizer类型:

import type { MergeCustomizer } from 'lodash';

const customizer: MergeCustomizer = (a, b) => {
  return _.isNull(b) ? a : b;
};

const merged = _.mergeWith(child, parent, customizer);

为什么不推荐用:any

指定:any会完全跳过TypeScript的类型检查,后续如果a或b的类型发生变化,或者合并逻辑出现错误,TypeScript无法及时给出提示,容易引入隐性bug。上述方案既能消除ESLint错误,又能保持类型安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:35:15