-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Description
2757 - PartialByKeys
This Challenge feels like the spiritual successor to Pick, Partial, and Omit: but with some extra fun sprinkled in for merging object intersections. Good times, good times. Tune in today to find out how to make a type that can make certain keys optional but not others.
🎥 Video Explanation
🔢 Code
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
interface User {
name: string
age: number
address: string
}
interface UserPartialName {
name?: string
age: number
address: string
}
interface UserPartialNameAndAge {
name?: string
age?: number
address: string
}
type A1 = PartialByKeys<User, 'name'>;
type B1 = UserPartialName;
type C1 = Expect<Equal<A1, B1>>;
type A2 = PartialByKeys<User, 'name' | 'age'>;
type B2 = UserPartialNameAndAge;
type C2 = Expect<Equal<A2, B2>>;
type A3 = PartialByKeys<User>;
type B3 = Partial<User>;
type C3 = Expect<Equal<A3, B3>>;
// @ts-expect-error(2344)
type E1 = PartialByKeys<User, 'name' | 'unknown'>;
// ============= Your Code Here =============
type MergeIntersection<T> = {
[P in keyof T]: T[P];
}
type PartialByKeys<
T,
K extends keyof T = keyof T
> = MergeIntersection<{
[P in keyof T as P extends K ? P : never]?: T[P]
} & {
[P in keyof T as P extends K ? never : P]: T[P]
}>
// ============== Alternatives ==============
type Copy<T> = Pick<T, keyof T>;
type PartialByKeys<
T,
K extends keyof T = keyof T
> =
Copy<
Partial<Pick<T, K>>
& Omit<T, K>
>;➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
No labels