PickByType
介绍
从类型'T'中, 筛选出属性类型位'U'的集合
例如:
ts
type OnlyBoolean = PickByType<{name: stringcount: numberisReadonly: booleanisEnable: boolean}, boolean> // { isReadonly: boolean; isEnable: boolean; }
View on GitHubts
type OnlyBoolean = PickByType<{name: stringcount: numberisReadonly: booleanisEnable: boolean}, boolean> // { isReadonly: boolean; isEnable: boolean; }
起点
ts
/* _____________ Your Code Here _____________ */typePickByType <T ,U > = any/* _____________ Test Cases _____________ */interfaceModel {name : stringcount : numberisReadonly : booleanisEnable : boolean}typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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 }>>,]
take the challengets
/* _____________ Your Code Here _____________ */typePickByType <T ,U > = any/* _____________ Test Cases _____________ */interfaceModel {name : stringcount : numberisReadonly : booleanisEnable : boolean}typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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 }>>,]
解决方案
Spoiler warning // Click to reveal answer
ts
typePickByType <T ,U > = {[K in keyofT asT [K ] extendsU ?K : never]:T [K ]}
ts
typePickByType <T ,U > = {[K in keyofT asT [K ] extendsU ?K : never]:T [K ]}