-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Labels
2595answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English
Description
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
🔢 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
Labels
2595answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English