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

2852 - OmitByType (🎥 Video Explanation and Solution) #23744

@dimitropoulos

Description

@dimitropoulos

2852 - OmitByType

Similar to PickByType (a previous challenge) this is a bit of an expansion pack on the Omit challenge (and, builtin). It's a good exercise that will challenge your memory of how to implement Omit.

🎥 Video Explanation

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

OmitByType

🔢 Code

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

interface Model {
  name: string
  count: number
  isReadonly: boolean
  isEnable: boolean
}

type A1 = OmitByType<Model, boolean>;
type B1 = {
  name: string;
  count: number
};
type C1 = Expect<Equal<A1, B1>>;

type A2 = OmitByType<Model, string>;
type B2 = {
  count: number;
  isReadonly: boolean;
  isEnable: boolean
};
type C2 = Expect<Equal<A2, B2>>;

type A3 = OmitByType<Model, number>;
type B3 = {
  name: string;
  isReadonly: boolean;
  isEnable: boolean
};
type C3 = Expect<Equal<A3, B3>>;

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

type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};
type Exclude<T, U> =
  T extends U
  ? never
  : T;
type Omit<T, K extends PropertyKey> =
  Pick<
    T,
    Exclude<keyof T, K>
  >;

type OmitByType<T, K> = {
  [P in keyof T as T[P] extends K ? never : P]: T[P]
}

// ============== Alternatives ==============
// credit to @z-juln
type KeyByType<T extends object, K> =
  keyof T extends `${infer P}` // grab specific keys
  ? P extends keyof T
    ? T[P] extends K
      ? P
      : never
    : never
  : never;

type OmitByType<T extends object, K> = {
  [P in Exclude<keyof T, KeyByType<T, K>>]: T[P]
};

➕ 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