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

59 - Get Optional (🎥 Video Explanation and Solution) #25063

@dimitropoulos

Description

@dimitropoulos

59 - Get Optional

If you solved yesterday's challenge (GetRequired) then this one should take all of 30 seconds to solve. There's a little bunch of 4 challenges here (starting with yesterday's) that are all related.

🎥 Video Explanation

Release Date: 2023-03-31 19:00 UTC

Get Optional

🔢 Code

// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'

type A1 = GetOptional<{ foo: number; bar?: string }>;
type B1 = { bar?: string };
type C1 = Expect<Equal<A1, B1>>;

type A2 = GetOptional<{ foo: undefined; bar?: undefined }>;
type B2 = { bar?: undefined };
type C2 = Expect<Equal<A2, B2>>;

// ============= Your Code Here =============
type GetOptional<T> = {
  [
    P in keyof T as
      T[P] extends Required<T>[P]
      ? never
      : P
  ]: T[P];
};

// ============== Alternatives ==============
// @Jack-Works
type GetRequired<T> = {
  [
    P in keyof T as
      T[P] extends Required<T>[P]
      ? P
      : never
  ]: T[P];
};
type GetOptional<T> = Omit<T, keyof GetRequired<T>>


// sneak peak from @yi-tuan:
type GetOptional<T> = Pick<T, OptionalKeys<T>>;

// @dqn
type GetOptional<
  T,
  U extends Required<T> = Required<T>,
  K extends keyof T = keyof T
> =
  Pick<
    T,
    K extends keyof T
    ? T[K] extends U[K]
      ? never
      : K
    : never
  >;

➕ 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