Last active
September 18, 2020 20:54
-
-
Save lindskogen/4785621167c99646ffa53d73bd3d656a to your computer and use it in GitHub Desktop.
Typescript Pick by value type
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
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