如何处理lodash.omitBy返回值的类型?
omitFalsyFields
泛型函数将删除值为 falsy 的键(''
、undefined
、null
等。 .) 的一个对象。
import _, { Dictionary } from 'lodash';
export function omitFalsyFields<T extends Dictionary<any>>(params: T) {
return _.omitBy(params, (k) => !k);
}
interface CreateUserParams {
name?: string;
email: string;
}
const params: CreateUserParams = omitFalsyFields({ name: '', email: '[email protected]' })
我期望它的返回值的类型是CreateUserParams
类型。 params
的值为 { email: '[email ;protected]' }
,因此类型是兼容的使用CreateUserParams
。
但是,出现 TS 类型错误:
“Dictionary”类型中缺少属性“email”,但“CreateUserParams”类型中需要属性“email”
omitFalsyFields
generic function will remove the key which value is falsy(''
, undefined
, null
, etc...) of an object.
import _, { Dictionary } from 'lodash';
export function omitFalsyFields<T extends Dictionary<any>>(params: T) {
return _.omitBy(params, (k) => !k);
}
interface CreateUserParams {
name?: string;
email: string;
}
const params: CreateUserParams = omitFalsyFields({ name: '', email: '[email protected]' })
I expect the type of its returned value is CreateUserParams
type. The value of params
is { email: '[email protected]' }
, so the type is compatible with CreateUserParams
.
But, got TS type error:
Property 'email' is missing in type 'Dictionary' but required in type 'CreateUserParams'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想使此函数通用,您可以执行以下操作:
现在您可以传递任何类型,并且它应该应用于输入和输出
但是对此需要注意的是
omitBy
返回一个Dictionary
,即使执行Dictionary
它也总是会强制转换为 any,因为有时很难在运行时推断类型(如果不是不可能的话),因此如果您想分配一个风俗返回类型或将通用 T 类型指定为输出,请执行以下操作:这样做,特定类型也会传递到输出,请查看 完整示例。
If you want to make this function generic, you can do the following:
Now you can pass any type and it should be applied to the input and output
But one caveat about this is that
omitBy
returns aDictionary<any>
, even doingDictionary<T>
it will always casts to any because it's very hard to infer types at runtime if not impossible sometimes, therefore if you want to assign a custom return type or assign the generic T type as output, do the following:Doing so, the specific type will be passed to the output as well, take a look at the complete example.