It's interesting how omit
doesn't automatically infer types by itself. I'm not sure why that is, but I've devised a helper function that should solve the issue.
function omitWithTypes<A extends ReadonlyArray<keyof B>, B extends Object>(
typeArray: A,
obj: B
) {
return omit(typeArray)(obj) as Omit<B, A[number]>;
}
The Omit utility type enables you to specify properties of a type. However, if you need to transform array values into a union type and pass them to Omit
, the array must be read-only. You can achieve this by using the as const
assertion to inform the TS compiler that it won't change.
const filter = ["serializedSvg", "svgSourceId"] as const;
const exclusive = omitWithTypes(filter, props);
OR
const exclusive = omitWithTypes(["serializedSvg", "svgSourceId"] as const, props);
You'll receive accurate inferred types (although it may seem a bit lengthy as it employs the Pick
utility type in the background):
https://i.sstatic.net/XqO2c.png
If you attempt to exclude values that aren't object properties, an error will arise:
https://i.sstatic.net/PPW6Y.png