Jingyi Wang
Jingyi Wang

Reputation: 956

Delete property of generic type

I have the following generic function and I want to replace any with < T >.

export const deleteFile = async (item: any, propName: string) => {
  const url = item[propName];
  await deleteFileByUrl(url);
  return omit<any>(item, propName);
};

I struggle to define a T which has a [propName]: string property and then return a type T without that property.

Upvotes: 2

Views: 1035

Answers (1)

spender
spender

Reputation: 120400

Combining a destructure with the Omit type, you could do something like:

export const deleteProperty = <T, K extends keyof T>(obj: T, id: K): Omit<T, K> => {
    const { [id]: _, ...newState } = obj;
    return newState;
};

Upvotes: 5

Related Questions