这是indexloc提供的服务,不要输入任何密码
Skip to content

399 - Tuple Filter (🎥 Video Explanation and Solution) #25924

@dimitropoulos

Description

@dimitropoulos

399 - Tuple Filter

TupleFilter is perhaps one of the most straightforward and also one of the most useful hard-difficulty challenge. This is, for once (haha), something that is genuinely useful to understand how to do in your day-to-day TypeScript development.

🎥 Video Explanation

Release Date: 2023-04-11 19:00 UTC

Tuple Filter

🔢 Code

// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'

type A1 = FilterOut<[], never>;
type B1 = [];
type C1 = Expect<Equal<A1, B1>>;

type A2 = FilterOut<[never], never>;
type B2 = [];
type C2 = Expect<Equal<A2, B2>>;

type A3 = FilterOut<['a', never], never>;
type B3 = ['a'];
type C3 = Expect<Equal<A3, B3>>;

type A4 = FilterOut<[1, never, 'a'], never>;
type B4 = [1, 'a'];
type C4 = Expect<Equal<A4, B4>>;

type A5 = FilterOut<
  [never, 1, 'a', undefined, false, null],
  never | null | undefined
>;
type B5 = [1, 'a', false];
type C5 = Expect<Equal<A5, B5>>;

type A6 = FilterOut<
  [number | null | undefined, never],
  never | null | undefined
>;
type B6 = [number | null | undefined];
type C6 = Expect<Equal<A6, B6>>;

// ============= Your Code Here =============
type FilterOut<T, Pred> =
  T extends [infer Head, ...infer Tail]
  ? [Head] extends [Pred]
    ? FilterOut<Tail, Pred>
    : [Head, ...FilterOut<Tail, Pred>]
  : [];

// @uid11
type FilterOut<T, Pred> =
  T extends [] // `can skip this whole section`
  ? []
  : T extends [infer Head, ...infer Tail]
    ? [Head] extends [Pred]
      ? FilterOut<Tail, Pred>
      : [Head, ...FilterOut<Tail, Pred>]
    : unknown[] // can remove `unknown`

➕ More Solutions

For more video solutions to other challenges: see the umbrella list! #21338

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions