Skip to content

Instantly share code, notes, and snippets.

@publicJorn
Created June 16, 2024 09:37
Show Gist options
  • Save publicJorn/57408873a9d37ca9b1e5f3b68255440a to your computer and use it in GitHub Desktop.
Save publicJorn/57408873a9d37ca9b1e5f3b68255440a to your computer and use it in GitHub Desktop.
Custom utility type to filter or remove types
// 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