Typescript 我可以让lodash省略返回特定类型而不是部分类型吗?

Typescript 我可以让lodash省略返回特定类型而不是部分类型吗?,typescript,lodash,Typescript,Lodash,在下面的代码中 import omit from "lodash/fp/omit"; type EnhancerProps = { serializedSvg: string; svgSourceId: string; containerId: string; }; const rest = omit(["serializedSvg", "containerId"])(props); rest被键入为Partial。我该怎么做才能让omit返回更具体的内容,比如说{svgSou

在下面的代码中

import omit from "lodash/fp/omit";

type EnhancerProps = {
  serializedSvg: string;
  svgSourceId: string;
  containerId: string;
};

const rest = omit(["serializedSvg", "containerId"])(props);

rest被键入为Partial。我该怎么做才能让omit返回更具体的内容,比如说
{svgSourceId:string}

奇怪的是
omit
不能自己推断类型。我不确定是否有这样的原因,但我能够想出一个助手函数,应该可以做到这一点

function omitWithTypes<A extends ReadonlyArray<keyof B>, B extends Object>(
  typeArray: A,
  obj: B
) {
  return omit(typeArray)(obj) as Omit<B, A[number]>;
}

您将获得正确的推断类型(尽管有点冗长,因为它在幕后使用了
Pick
实用程序类型):

如果您试图排除不是从中拾取的对象属性的值,甚至会出现错误:


不确定TS能否准确推断出您在此处排除的内容。它所知道的是,您从某种类型的
T
开始,而
T
的属性(可能)会更少。如果它知道是哪些,那么它可以使用
Exclude
helper,但是您可以将任何数组传递给
ommit
。如果要省略的键总是相同的,那么可以使用包装器函数执行某些操作。“奇怪的是,
ommit
不能自行推断类型”让我给你两个理由:1。“阵列必须为只读”2。“如果您试图排除不是从中拾取的对象属性的值,甚至会出现错误”。这两种方法都会使
省略
更难用于一般用途。
const filter = ["serializedSvg", "svgSourceId"] as const;
const exclusive = omitWithTypes(filter, props);
const exclusive = omitWithTypes(["serializedSvg", "svgSourceId"] as const, props);