能否让lodash省略返回特定类型而不是部分类型?

问题描述 投票:0回答:1

在下面的代码中

import omit from "lodash/fp/omit";

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

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

rest被输入为Partial。我怎样才能让省略返回更具体的东西,如 {svgSourceId: string} 代替。

typescript lodash
1个回答
2
投票

奇怪的是 omit 并不能自行推断类型。我不知道是否有这样的原因,但是我想出了一个辅助函数,应该可以做到这一点。

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

这个 省略 实用类型将允许你缩小类型的属性。然而,如果你想把一个数组的值转换为联合类型,并传递给 Omit阵列 必须 只读,你可以通过以下方式来满足。as const 主张 来告诉TS编译器它不会突变。

const filter = ["serializedSvg", "svgSourceId"] as const;
const exclusive = omitWithTypes(filter, props);

const exclusive = omitWithTypes(["serializedSvg", "svgSourceId"] as const, props);

你会得到正确的推断类型(尽管它有点啰嗦,因为它使用的是 Pick 后面的实用类型)。)

enter image description here

如果你试图排除那些不是被选中对象的属性的值,你甚至会得到一个错误。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.