Skip to content

Instantly share code, notes, and snippets.

@lindskogen
Last active September 18, 2020 20:54
Show Gist options
  • Save lindskogen/4785621167c99646ffa53d73bd3d656a to your computer and use it in GitHub Desktop.
Save lindskogen/4785621167c99646ffa53d73bd3d656a to your computer and use it in GitHub Desktop.
Typescript Pick by value type
type ExtractKeysByValueType<O, V> = {
[P in keyof O]: O[P] extends V ? P : never;
}[keyof O]
type PickByValueType<O, V> = Pick<O, ExtractKeysByValueType<O, V>>
type OmitByValueType<O, V> = Omit<O, ExtractKeysByValueType<O, V>>
// Usage:
interface User {
id: string;
name: string;
age: number;
isAdmin: boolean;
}
// Only the properties in User that are strings
type A = PickByValueType<User, string> // { id: string; name: string }
// Everything but the properties in User that are strings
type B = OmitByValueType<User, string> // { age: number; isAdmin: boolean }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment