create function for omit in typescript

Here's an implementation of the omit function in TypeScript, which creates a new object without the specified key(s):

index.ts
function omit<T extends object, K extends keyof T>(obj: T, ...keys: K[]): Omit<T, K> {
  const result = {} as Omit<T, K>;

  for (const key in obj) {
    if (!keys.includes(key as K)) {
      result[key] = obj[key];
    }
  }

  return result;
}
246 chars
12 lines

This implementation uses generics to ensure that the input object is of a specific type, and that the omitted keys are only those that exist in the input type's keys. It also uses the Omit utility type to ensure that the returned object does not have the omitted keys.

Here's an example of how to use this function:

index.ts
interface Person {
  name: string;
  age: number;
  email: string;
}

const person: Person = {
  name: "Alice",
  age: 30,
  email: "alice@example.com",
};

const withoutEmail = omit(person, "email");
// withoutEmail: { name: string; age: number; }
249 chars
15 lines

gistlibby LogSnag