Created
October 6, 2022 07:46
-
-
Save semlinker/b33f05cd095d94c03c5c95748287b9b9 to your computer and use it in GitHub Desktop.
Implement a generic RequiredByKeys<T, K> which takes two type argument T and K.
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 User { | |
name?: string | |
age?: number | |
address?: string | |
} | |
type RequiredByKeys<T, K = keyof T> = Merge< | |
{ | |
[P in keyof T as P extends K ? P : never]-?: T[P] | |
} & { | |
[P in keyof T as P extends K ? never : P]: T[P] | |
} | |
> | |
type Merge<T> = { | |
[P in keyof T]: T[P] | |
} | |
type UserRequiredName = RequiredByKeys<User, 'name'> | |
// { name: string; age?: number; address?: string } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment