[TypeScript] Type Challenges #2070 - Drop Char

63 阅读1分钟

题目描述

从字符串中剔除指定字符。

例如:

type Butterfly = DropChar<' b u t t e r f l y ! ', ' '> // 'butterfly!'

题解

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

type cases = [
  // @ts-expect-error
  Expect<Equal<DropChar<'butter fly!', ''>, 'butterfly!'>>,
  Expect<Equal<DropChar<'butter fly!', ' '>, 'butterfly!'>>,
  Expect<Equal<DropChar<'butter fly!', '!'>, 'butter fly'>>,
  Expect<Equal<DropChar<'    butter fly!        ', ' '>, 'butterfly!'>>,
  Expect<Equal<DropChar<' b u t t e r f l y ! ', ' '>, 'butterfly!'>>,
  Expect<Equal<DropChar<' b u t t e r f l y ! ', 'b'>, '  u t t e r f l y ! '>>,
  Expect<Equal<DropChar<' b u t t e r f l y ! ', 't'>, ' b u   e r f l y ! '>>,
]


// ============= Your Code Here =============
type DropChar<T extends string, C extends string> =
  T extends `${infer Left}${C}${infer Right}`
    ? `${Left}${DropChar<Right, C>}`
    : T;

条件类型

type DropChar<T extends string, C extends string> =
  T extends `${infer Left}${C}${infer Right}`
    ? `${Left}${DropChar<Right, C>}`
    : T;
  • 条件判断:

    • T extends ${infer Left}${C}${infer Right},如果T包含C,则将T拆分为三部分:

      • LeftC之前的部分

      • C:指定字符

      • RightC之后的部分

    • 如果T包含C,则递归调用DropChar<Right, C>,继续剔除Right中的C

    • 如果T不包含C,则直接返回T