Created
April 4, 2021 05:36
-
-
Save njbmartin/a1ee22d07c22d05687b6e753c7a302ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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