Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created October 6, 2022 07:46
Show Gist options
  • Save semlinker/b33f05cd095d94c03c5c95748287b9b9 to your computer and use it in GitHub Desktop.
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.
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