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

2595 - PickByType (🎥 Video Explanation and Solution) #23720

@dimitropoulos

Description

@dimitropoulos

2595 - PickByType

Finally (you may be thinking), a type that you could see yourself actually needing! PickByType is a rare opportunity to solve a challenge that might actually be useful in day-to-day development. It acts as a kind of filter with a predicate where you can filter out the values of a type's properties.

🎥 Video Explanation

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

PickByType

🔢 Code

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

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

type A1 = PickByType<Model, boolean>;
type B1 = { isReadonly: boolean; isEnable: boolean };
type C1 = Expect<Equal<A1, B1>>;

type A2 = PickByType<Model, string>;
type B2 = { name: string };
type C2 = Expect<Equal<A2, B2>>;

type A3 = PickByType<Model, number>;
type B3 = { count: number };
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];
}

➕ More Solutions

For more video solutions to other challenges: see the umbrella list! #21338

Metadata

Metadata

Assignees

No one assigned

    Labels

    2595answerShare answers/solutions to a questionenin English

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions