跳到主要内容

PickByType

介绍

从类型'T'中, 筛选出属性类型位'U'的集合

例如:

ts
type OnlyBoolean = PickByType<{
name: string
count: number
isReadonly: boolean
isEnable: boolean
}, boolean> // { isReadonly: boolean; isEnable: boolean; }
ts
type OnlyBoolean = PickByType<{
name: string
count: number
isReadonly: boolean
isEnable: boolean
}, boolean> // { isReadonly: boolean; isEnable: boolean; }
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type PickByType<T, U> = any
 
/* _____________ Test Cases _____________ */
 
interface Model {
name: string
count: number
isReadonly: boolean
isEnable: boolean
}
type cases = [
Expect<Equal<PickByType<Model, boolean>, { isReadonly: boolean, isEnable: boolean }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<PickByType<Model, string>, { name: string }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<PickByType<Model, number>, { count: number }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
ts
/* _____________ Your Code Here _____________ */
 
type PickByType<T, U> = any
 
/* _____________ Test Cases _____________ */
 
interface Model {
name: string
count: number
isReadonly: boolean
isEnable: boolean
}
type cases = [
Expect<Equal<PickByType<Model, boolean>, { isReadonly: boolean, isEnable: boolean }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<PickByType<Model, string>, { name: string }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<PickByType<Model, number>, { count: number }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
type PickByType<T, U> = {
[K in keyof T as T[K] extends U ? K : never]: T[K]
}
 
ts
type PickByType<T, U> = {
[K in keyof T as T[K] extends U ? K : never]: T[K]
}
 
view more solutions