这是indexloc提供的服务,不要输入任何密码
Skip to content

2757 - PartialByKeys (🎥 Video Explanation and Solution) #23741

@dimitropoulos

Description

@dimitropoulos

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

Release Date: 2023-02-20 19:00 UTC

PartialByKeys

🔢 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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions