跳到主要内容

OmitByType

介绍

从类型T中, 筛选属性类型不能赋值为'U'的属性集合.

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

起点

ts
/* _____________ Your Code Here _____________ */
 
type OmitByType<T, U> = any
 
/* _____________ Test Cases _____________ */
 
interface Model {
name: string
count: number
isReadonly: boolean
isEnable: boolean
}
 
type cases = [
Expect<Equal<OmitByType<Model, boolean>, { name: string, count: number }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<OmitByType<Model, string>, { count: number, isReadonly: boolean, isEnable: boolean }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<OmitByType<Model, number>, { name: string, isReadonly: boolean, isEnable: boolean }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
ts
/* _____________ Your Code Here _____________ */
 
type OmitByType<T, U> = any
 
/* _____________ Test Cases _____________ */
 
interface Model {
name: string
count: number
isReadonly: boolean
isEnable: boolean
}
 
type cases = [
Expect<Equal<OmitByType<Model, boolean>, { name: string, count: number }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<OmitByType<Model, string>, { count: number, isReadonly: boolean, isEnable: boolean }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<OmitByType<Model, number>, { name: string, isReadonly: boolean, isEnable: boolean }>>,
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 OmitByType<T, U> = {
[P in keyof T as T[P] extends U ? never : P]: T[P]
}
 
ts
 
type OmitByType<T, U> = {
[P in keyof T as T[P] extends U ? never : P]: T[P]
}
 
view more solutions