Skip to content

Instantly share code, notes, and snippets.

@njbmartin
Created April 4, 2021 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njbmartin/a1ee22d07c22d05687b6e753c7a302ed to your computer and use it in GitHub Desktop.
Save njbmartin/a1ee22d07c22d05687b6e753c7a302ed to your computer and use it in GitHub Desktop.
interface Person {
firstName: string;
lastName: string;
email: string;
phone: string;
}
type PersonWithoutEmail = Omit<Person, "email">
type PersonWithoutEmailOrPhone = Omit<Person, "email" | "phone">
const person: Person = {
firstName: "Jane",
lastName: "Bloggs",
email: "jane@example.com",
phone: "0123456789"
};
const omitKey = <T, K extends keyof T>(data: T, key: K) => {
const { [key]: _, ...o } = data;
return o;
}
const omitKeys = <T, K extends keyof T>(data: T, keys: K[]): Omit<T, K> => {
return keys.reduce((curr, key) =>
(keys.includes(key) ? curr : { ...curr, [key]: data[key] })
, {} as Omit<T, K>)
}
console.log(person);
const personWithoutEmail: PersonWithoutEmail = omitKey(person, "email")
console.log(personWithoutEmail)
const safePerson: PersonWithoutEmailOrPhone = omitKeys(person, ["email", "phone"])
console.log(safePerson)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment