[Typescript] 132. Medium - Filter

Implement the type Filter<T, Predicate> takes an Array T, primitive type or union primitive type Predicate and returns an Array include the elements of Predicate.

 

/* _____________ Your Code Here _____________ */

type Filter<T extends any[], U, ACC extends any[] = []> = T extends [infer F, ...infer RT]
  ? F extends U
    ? Filter<RT, U, [...ACC, F]>
    : Filter<RT, U, ACC>
  : ACC;

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type Falsy = false | 0 | '' | null | undefined

type cases = [
  Expect<Equal<Filter<[0, 1, 2], 2>, [2]>>,
  Expect<Equal<Filter<[0, 1, 2], 0 | 1>, [0, 1]>>,
  Expect<Equal<Filter<[0, 1, 2], Falsy>, [0]>>
]

 

posted @ 2022-12-11 17:26  Zhentiw  阅读(12)  评论(0编辑  收藏  举报