Created
June 16, 2024 09:37
-
-
Save publicJorn/57408873a9d37ca9b1e5f3b68255440a to your computer and use it in GitHub Desktop.
Custom utility type to filter or remove types
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
// Playground: https://www.typescriptlang.org/play/?#code/PTAEBUE8AcFNWgJwPYHNEEMC2WCWA7VAKBFAHFkMAbALlADNcqAXWRUDUACgGdZnQyegEpQzGLB4MUWDvmTMAFmzESSYRc2bQeNEACMqaAHQBrXEmQ9FxgMbIswWwFcezBwFpnzJrnEfxOB4PAgCJHltEC2ZgIiJA+AAFNh5kfABJfHpkUABeUABvIlBQfGxYOjcowgBuYo5UCtLnLH02OpLoRTSm-Ba2xA7QAEdnBSaqglQhgHdkRFM6LlFcgD5QADdkXAATIgBfOviJUAAlWCxkDdgAaVhIHgB5eig4AB5X2AAaUDvIdfyRRKAG1TPdQARQGDIEIICcMFJPqD7gBdUCwAAerHwOykf1AAH5SrBruw6NCUXQkRS6oc4glQAAxJisRB-J4vCQfCQ-P4Awr1ZGQCH4KH3WGfDiIiRCtGY7G437gonQ0B0fAktiUuFwWW0o7HOCgADqfm63gAcv0Unkzhcrrd7hzPm9kohUhkssgfn1WmxVkcGY98FRIFa-e7bcyWGx2c8XW6PZlsj7rYgA-STsHQ+GBjwAII4gDKzGqqCk+WjrLjnPeibSye9zQjoAAPqBJoRVkQgA | |
// Type programming | |
// Goal: filter a (set of) types from another type | |
// https://blog.kiprosh.com/custom-utility-types-in-typescript/ | |
type PersonInfo = { | |
name: string; | |
age: number; | |
phone: number; | |
quote: string; | |
work: () => void | |
}; | |
type RemoveKeysOfType<Type, Key> = { | |
[key in keyof Type as Type[key] extends Key ? never : key]: Type[key]; | |
}; | |
type FilterKeysOfType<Type, Key> = { | |
[key in keyof Type as Type[key] extends Key ? key : never]: Type[key]; | |
}; | |
type WithoutNumbers = RemoveKeysOfType<PersonInfo, number>; | |
type OnlyNumbers = FilterKeysOfType<PersonInfo, number>; | |
type OnlyNumbersAndStrings = FilterKeysOfType<PersonInfo, number | string> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment