Home > OS >  Typescript: expand generic array type into a generic union type
Typescript: expand generic array type into a generic union type

Time:11-09

So what I want to achieve is following: I have type P which represents array of keys from an object T, so P extends Array<keyof T>. And I want to pass the P to Omit<T, P> to exclude given keys from that objects.

In TS code it looks like this

export function excludeProps<T extends Record<string, any>, P extends Array<keyof T>>(
  object: T,
  ...propsToExclude: P
): Omit<T, P> {
  const filteredEntries = Object.entries(object).filter(([key]) => !propsToExclude.includes(key));
  return Object.fromEntries(filteredEntries);
}

This of course doesn't work because Omit expects a single key or union of keys, not an array. Is there a way to transform P so that it can be passed in? Or is there a better way to type this?

CodePudding user response:

Its quite simple: turn the elements of the array into a union type by indexing with [number].

export function excludeProps<
  T extends Record<string, any>, 
  P extends Array<keyof T>
>(
  object: T,
  ...propsToExclude: P
): Omit<T, P[number]> {
  const filteredEntries = Object.entries(object).filter(([key]) => !propsToExclude.includes(key));
  return Object.fromEntries(filteredEntries) as Omit<T, P[number]>
}

Also, you are gonna need a type assertion for the return type.


Playground

  • Related